Sequelize

其他 ORM:



Sequelize is a promise-based ORM for Node.js and io.js. It supports the dialects PostgreSQL, MySQL,MariaDB, SQLite and MSSQL and features solid transaction support, relations, read replication and more.

var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password'); // 链接数据库


var User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE
}); // 定义 User model


sequelize.sync().then(function() { // 自动建立 tables
return User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20)
});
}).then(function(jane) { // 创建完成,返回创建的包装对象
console.log(jane.get({
plain: true // ???
}));
});

Sequelize supports adding indexes to the model definition which will be created during Model.sync() or sequelize.sync.



// 事物
sequelize.transaction().then(transaction => {
return User.find(..., {transaction})
.then(user => user.updateAttributes(..., {transaction}))
.then(() => transaction.commit())
.catch(() => transaction.rollback());
})