Sequelize简单好上手的node.js ORM框架[MarkDown Note]

Posted 一步一步似爪牙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sequelize简单好上手的node.js ORM框架[MarkDown Note]相关的知识,希望对你有一定的参考价值。

前言

轻量应用开发,node.js足够

前些天,在学习开发微信小程序的时候,感觉到了腾讯的人性化,微信公众平台竟然免费提供了一个开发环境与一个生产环境,提供腾讯云的服务,不过只支持php与node.js的开发语言。在此情况下,我毅然决然的入手了node.js来支持我的小程序后台开发。

今天我先简单给大家介绍一门 ORM(object relation mapping) 对象关系映射型的node.js框架--Sequelize

1.安装

Sequelize支持通过npm与yarn进行安装

Sequelize安装很简单,可以通过npm与yarn进行安装,也支持使用淘宝镜像cnpm进行安装。

 
   
   
 
  1. // 使用 NPM(使用cnpm类似)

  2. $ npm install --save sequelize

  3. # 下面的数据库支持的包任选一种安装:

  4. $ npm install --save pg pg-hstore

  5. $ npm install --save mysql2   //mysql

  6. $ npm install --save sqlite3  //sqlite

  7. $ npm install --save tedious // MSSQL

  8. // Using Yarn

  9. $ yarn add sequelize

  10. # And one of the following:

  11. $ yarn add pg pg-hstore

  12. $ yarn add mysql2

  13. $ yarn add sqlite3

  14. $ yarn add tedious // MSSQL

2.创建连接

初始化创建连接及连接池

  1. 安装好sequelize之后,我们可以新建一个js文件定义为db.js

  2. 导入sequelize包,并通过实例化Sequelize创建连接,我们使用的是mysql数据库,具体代码如下:

 
   
   
 
  1. const Sequelize = require('sequelize');

  2. const sequelize = new Sequelize('temp_work', 'root', 'root', {

  3.  host: 'localhost',

  4.  dialect: 'mysql',

  5.  operatorsAliases: false,

  6.  //定义连接池

  7.  pool: {

  8.    max: 5,

  9.    min: 0,

  10.    acquire: 30000,

  11.    idle: 10000

  12.  },

  13. });

根据官方的文档,创建连接,传参中具有下列选项(以下为本人翻译):

 
   
   
 
  1. const sequelize = new Sequelize('database', 'username', 'password', {

  2.  // 定义sql的方言

  3.  // 目前支持: 'mysql', 'sqlite', 'postgres', 'mssql'

  4.  dialect: 'mysql',

  5.  // 客户主机; 默认: localhost

  6.  host: 'my.server.tld',

  7.  // 客户端 端口; 默认: 方言默认的

  8.  port: 12345,

  9.  // 客户协议  默认tcp;

  10.  // postgres only, useful for Heroku

  11.  protocol: null,

  12.  // 设置关闭日志; 默认: console.log

  13.  logging: false,

  14.  // 你可以把任何方言协议放在方言库下面

  15.  // - 默认是空的

  16.  // - 当前支持: 'mysql', 'postgres', 'mssql'

  17.  dialectOptions: {

  18.    socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock',

  19.    supportBigNumbers: true,

  20.    bigNumberStrings: true

  21.  },

  22.  // sqlite的存储引擎

  23.  // - 默认 ':内存:'

  24.  storage: 'path/to/database.sqlite',

  25.  // 取消插入未定义的数据为null

  26.  // - 默认: false

  27.  omitNull: true,

  28.  // 是否使用本地包的一个flag标志

  29.  // 在 'pg'的情况下 -- 设置这个为true将支持 SSL

  30.  // - default: false

  31.  native: true,

  32.  // 特殊选项 options, 当 sequelize.define被调用的时候使用.

  33.  // 例如:

  34.  //   define: { timestamps: false }

  35.  // 类似于:

  36.  //   sequelize.define(name, attributes, { timestamps: false })

  37.  // 所以给每一个模型定义时间戳不是必须的

  38.  define: {

  39.    underscored: false

  40.    freezeTableName: false,

  41.    charset: 'utf8',

  42.    dialectOptions: {

  43.      collate: 'utf8_general_ci'

  44.    },

  45.    timestamps: true

  46.  },

  47.  // 与同步sync相同: 你可以定义始终强制同步models模型

  48.  sync: { force: true },

  49.  // 连接池配置用于与数据库创建连接池

  50.  pool: {

  51.    max: 5,

  52.    idle: 30000,

  53.    acquire: 60000,

  54.  },

  55.  // 每一笔事务transaction的隔离登记

  56.  // 默认为方言所默认的

  57.  isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ

  58. })

3、测试连接

可以调用.authenticate()方法像下面的代码一行测试连接

 
   
   
 
  1. sequelize

  2. .authenticate()

  3. .then(() => {

  4.  console.log('Connection has been established successfully.');

  5. })

  6. .catch(err => {

  7.  console.error('Unable to connect to the database:', err);

  8. });

4、定义一个模型

使用sequelize.define('name', {attributes}, {options})来定义一个模型

 
   
   
 
  1. //创建一个User对象,关联user表

  2. //定义user表中的两个字段:String类型的firstName与String类型的lastName

  3. const User = sequelize.define('user', {

  4.    firstName: {

  5.      type: Sequelize.STRING

  6.    },

  7.    lastName: {

  8.      type: Sequelize.STRING

  9.    }

  10.  });

注意事项:默认情况下,sequelize会主动创建createdAt与updatedAt两个时间戳字段。

sequelize支持的数据类型(拆自官方文档):
 
   
   
 
  1. Sequelize.STRING                      // VARCHAR(255)

  2. Sequelize.STRING(1234)                // VARCHAR(1234)

  3. Sequelize.STRING.BINARY               // VARCHAR BINARY

  4. Sequelize.TEXT                        // TEXT

  5. Sequelize.TEXT('tiny')                // TINYTEXT

  6. Sequelize.INTEGER                     // INTEGER

  7. Sequelize.BIGINT                      // BIGINT

  8. Sequelize.BIGINT(11)                  // BIGINT(11)

  9. Sequelize.FLOAT                       // FLOAT

  10. Sequelize.FLOAT(11)                   // FLOAT(11)

  11. Sequelize.FLOAT(11, 12)               // FLOAT(11,12)

  12. Sequelize.REAL                        // REAL        PostgreSQL only.

  13. Sequelize.REAL(11)                    // REAL(11)    PostgreSQL only.

  14. Sequelize.REAL(11, 12)                // REAL(11,12) PostgreSQL only.

  15. Sequelize.DOUBLE                      // DOUBLE

  16. Sequelize.DOUBLE(11)                  // DOUBLE(11)

  17. Sequelize.DOUBLE(11, 12)              // DOUBLE(11,12)

  18. Sequelize.DECIMAL                     // DECIMAL

  19. Sequelize.DECIMAL(10, 2)              // DECIMAL(10,2)

  20. Sequelize.DATE                        // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres

  21. Sequelize.DATE(6)                     // DATETIME(6) for mysql 5.6.4+. Fractional seconds support with up to 6 digits of precision

  22. Sequelize.DATEONLY                    // DATE without time.

  23. Sequelize.BOOLEAN                     // TINYINT(1)

  24. Sequelize.ENUM('value 1', 'value 2')  // An ENUM with allowed values 'value 1' and 'value 2'

  25. Sequelize.ARRAY(Sequelize.TEXT)       // Defines an array. PostgreSQL only.

  26. Sequelize.ARRAY(Sequelize.ENUM)       // Defines an array of ENUM. PostgreSQL only.

  27. Sequelize.JSON                        // JSON column. PostgreSQL, SQLite and MySQL only.

  28. Sequelize.JSONB                       // JSONB column. PostgreSQL only.

  29. Sequelize.BLOB                        // BLOB (bytea for PostgreSQL)

  30. Sequelize.BLOB('tiny')                // TINYBLOB (bytea for PostgreSQL. Other options are medium and long)

  31. Sequelize.UUID                        // UUID datatype for PostgreSQL and SQLite, CHAR(36) BINARY for MySQL (use defaultValue: Sequelize.UUIDV1 or Sequelize.UUIDV4 to make sequelize generate the ids automatically)

  32. Sequelize.RANGE(Sequelize.INTEGER)    // Defines int4range range. PostgreSQL only.

  33. Sequelize.RANGE(Sequelize.BIGINT)     // Defined int8range range. PostgreSQL only.

  34. Sequelize.RANGE(Sequelize.DATE)       // Defines tstzrange range. PostgreSQL only.

  35. Sequelize.RANGE(Sequelize.DATEONLY)   // Defines daterange range. PostgreSQL only.

  36. Sequelize.RANGE(Sequelize.DECIMAL)    // Defines numrange range. PostgreSQL only.

  37. Sequelize.ARRAY(Sequelize.RANGE(Sequelize.DATE)) // Defines array of tstzrange ranges. PostgreSQL only.

  38. Sequelize.GEOMETRY                    // Spatial column.  PostgreSQL (with PostGIS) or MySQL only.

  39. Sequelize.GEOMETRY('POINT')           // Spatial column with geometry type. PostgreSQL (with PostGIS) or MySQL only.

  40. Sequelize.GEOMETRY('POINT', 4326)     // Spatial column with geometry type and SRID.  PostgreSQL (with PostGIS) or MySQL only.

除了上面提到的类型,integer, bigint, float 与 double 也支持unsigned与zerofill特性。它们能以任意顺序组合。需要注意的是PostgreSQL不支持
 
   
   
 
  1. Sequelize.INTEGER.UNSIGNED              // INTEGER UNSIGNED

  2. Sequelize.INTEGER(11).UNSIGNED          // INTEGER(11) UNSIGNED

  3. Sequelize.INTEGER(11).ZEROFILL          // INTEGER(11) ZEROFILL

  4. Sequelize.INTEGER(11).ZEROFILL.UNSIGNED // INTEGER(11) UNSIGNED ZEROFILL

  5. Sequelize.INTEGER(11).UNSIGNED.ZEROFILL // INTEGER(11) UNSIGNED ZEROFILL

5、执行查询操作

 
   
   
 
  1. //查询users表中的所有值

  2. User.findAll().then(users => {

  3.  console.log(users)

  4. })

  5. // 通过已知id查询数据

  6. User.findById(123).then(user => {

  7. })

  8. // 通过字段搜索一条记录

  9. User.findOne({ where: {firstName: 'hahaha'} }).then(user => {

  10. })

  11. //更新lastName为hahaha的那一条记录的firstName为gege

  12. User.update({firstName:'gege'},{where:{lastName:'hahaha'}}).then(user =>{

  13. })

  14. //删除lastName为hahaha的数据

  15. User.destroy({where:{lastName:'hahaha'}});

  16. //根据条件查询,如果没查到,就插入一条

  17. User

  18.  .findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead javascript'}})

  19.  .spread((user, created) => {

  20.    console.log(user.get({

  21.      plain: true

  22.    }))

  23.    console.log(created)

  24.  })

  25. //插入一条数据

  26. User.create({ username: 'fnord', job: 'omnomnom' })

  27.  .then(() => User.findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}}))

  28.  .spread((user, created) => {

  29.    console.log(user.get({

  30.      plain: true

  31.    }))

  32.    console.log(created)

  33.  })

  34. //求出年龄的和

  35. User.sum('age').then(sum => {

  36. })

  37. //找出最大值,max()中第二个参数可以传入条件{op:""}

  38. User.max('age').then(max => {

  39.  // this will return 40

  40. })

  41. //查询总记录条数

  42. User.count().then(c => {

  43. })

  44. …………<后续细说>

结:

看过这些demo之后,可以看出来sequelize其实很容易,很好轻松上手,如果喜欢,可以现在上手试试吧。


以上是关于Sequelize简单好上手的node.js ORM框架[MarkDown Note]的主要内容,如果未能解决你的问题,请参考以下文章

Python 操作Redis

python爬虫入门----- 阿里巴巴供应商爬虫

Python词典设置默认值小技巧

《python学习手册(第4版)》pdf

Django settings.py 的media路径设置

Python中的赋值,浅拷贝和深拷贝的区别