Sequelize 入门
安装
Sequelize 通过 NPM 包进行安装
$ npm install --save sequelize
# And one of the following:
$ npm install --save pg pg-hstore
$ npm install --save mysql // For both mysql and mariadb dialects
$ npm install --save sqlite3
$ npm install --save tedious // MSSQL
设置连接
Sequelize 在初始化的时候将设置一个连接池,所以你最好一个数据库只创建一个实例
var sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
},
// SQLite only
storage: 'path/to/database.sqlite'
});
// Or you can simply use a connection uri
var sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname');
Sequelize 构造函数的整体参数,具体情况可参考API reference
你的第一个模型
Sequelize 使用 sequelize.define('name', {attributes}, {options}) 定义模型
var User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING,
field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
},
lastName: {
type: Sequelize.STRING
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});
User.sync({force: true}).then(function () {
// Table created
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
更多的选项,请参考 Model API reference
应用广泛的模型选项
Sequelize 构造函数中有一个 define 的选项,它被用作所有定义的模型的默认选项。
var sequelize = new Sequelize('connectionUri', {
define: {
timestamps: false // true by default
}
});
var User = sequelize.define('user', {}); // timestamps is false by default
var Post = sequelize.define('post', {}, {
timestamps: true // timestamps will now be true
});
Promises
Sequelize 使用 Promises 来控制异步控制流. 如果你不熟悉 Promises 如何工作,现在可能是一个很好的时间了解他们,具体可参考 awesome-promises 与 why Promises
一般来说一个 promise 代表将存在在某一时刻的值 - ”我承诺我将返回给你在某个时刻的一个结果或者一个错误”,这将意味着
// DON'T DO THIS
user = User.findOne()
console.log(user.name);
将不会执行!这是因为 user 是一个 promise 对象,不是从数据库中的一行数据,正确的做法,应该是:
User.findOne().then(function (user) {
console.log(user.name);
});
一旦你掌握了 promises 是如何工作的,可以使用 bluebird API reference作为你的工具,在特定的情况下,你可能使用 .all 更多些。