前言
前一篇介绍了如何直连mysql,但是两种代码风格都有自身的弊端。这次主要探讨如何利用ORM操作数据库。
官方帮助文档:getting-started
安装
安装Sequelize:
1  | npm install --save sequelize  | 
根据连接的数据库的不同,需要手动安装对应的驱动:
1  | # One of the following:  | 
连接数据库
要连接数据库,必须创建一个sequelize实例。可以通过向构造函数传参数或者通过连接字符串创建
1  | const Sequelize = require('sequelize');  | 
如果是SQLite数据库:
1  | const sequelize = new Sequelize({  | 
我的代码:
1  | const Sequelize = require('sequelize');  | 
pool:每个实例创建一个最多5个连接的连接池
model:禁用每个表的createdAt和updatedAt自动更新,表名不会自动加上s
为每张表创建model
model是Sequelize.Model的子类,通过两种方法创建
第一种:Sequelize.Model.init(attributes, options):
1  | const Model = Sequelize.Model;  | 
第二种:sequelize.define:
1  | const User = sequelize.define('user', {  | 
在内部实现上,sequelize.define 调用 Model.init
上面的代码定义了一个users表,字段有id,firstName,lastName,createdAt,updatedAt
其中,表名的s是自动加上去的,通过在options里设置freezeTableName: true可以防止自动添加,或者通过Sequelize的构造函数里的option.define设置成默认不自动添加。createdAt和updatedAt同理。id是自动添加的主键。
同步model和数据库
如果你想让Sequelize通过model的定义自动创建(或按照需要修改)数据库表,可以用sync方法:
1  | // Note: 使用`force: true`如果表已存在会drop掉  | 
一次同步所有model
如果不想每个model都调用一次sync()方法,你可以调用sequelize.sync()方法,这将会同步所有model
生产环境
在生产环境,你可能需要考虑在你的代码中使用迁移来代替调用sync()。官方文档:Migrations
简单的增删改查
一些简单的语句:
1  | // Find all users  | 
Promises和async/await
Sequelize支持Promises,用的是bluebird。可以使用async/await语法糖,也可以使用bluebird的API( finally, tap, tapCatch, map, mapSeries, 等等)
数据类型
mysql常用的类型
1  | Sequelize.STRING // VARCHAR(255)  | 
In addition to the type mentioned above, integer, bigint, float and double also support unsigned and zerofill properties, which can be combined in any order: Be aware that this does not apply for PostgreSQL!
1  | Sequelize.INTEGER.UNSIGNED // INTEGER UNSIGNED  | 
The examples above only show integer, but the same can be done with bigint and float
Usage in object notation:
1  | // for enums:  |