经过比较个人感觉sequelize 比其他orm好用些,用了半天时间终于搞定了,直接上代码
1、利用sequelize model生成table
applicationMysql.js文件------------
var Sequelize = require('sequelize');
var sequelize = new Sequelize('db', 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
},
Sequelize :Sequelize
});
function ApplicationMysql(){
return sequelize;
}
module.exports = new ApplicationMysql();
user.js文件-----------------
var app = require('../server/applicationMysql.js');
User = app.define('user',{
firstName: {
type: app.Sequelize.STRING,
// field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
},
lastName: {
type: app.Sequelize.STRING
}
},{
freezeTableName: true // Model tableName will be the same as the model name
});
app.sync().then(function() {
User.create({
first_name: 'qi',
lastName: 'shuo'
});
});
module.exports = User;
加载var userModel = require('./user.js');数据库中就会生成user表
详见http://docs.sequelizejs.com/en/v3/
2、利用sequelize-auto table生成model
在数据库新建表
然后运行sequelize-auto -o "./mysqltest" -d db -h localhost -u root -p 3306 -x root -e mysql
在mysqltest目录下就会生成user.js
/* jshint indent: 2 */
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
first_name: {
type: DataTypes.STRING,
allowNull: true
},
lastName: {
type: DataTypes.STRING,
allowNull: true
},
type: {
type: DataTypes.STRING,
allowNull: true
},
createdAt: {
type: DataTypes.DATE,
allowNull: false
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false
}
}, {
tableName: 'user'
});
};
详见:https://www.npmjs.com/package/sequelize-auto
好了,有了这个写代码爽多了