传送门
# 视频教程 https://nodelover.me/course/sequelize/ # 官方文档 http://docs.sequelizejs.com/manual/tutorial/models-definition.html # sequelize-cli 文档 http://docs.sequelizejs.com/manual/tutorial/migrations.html#the-cli
数据库连接,以mysql为例
const Sequelize = require('sequelize');
const connect = new Sequelize('database', 'username', 'password', {
host: 'localhost',
port: 3306,
dialect: 'mysql',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
});
connect.authenticate().then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
model的创建和同步数据库
// 模型定义API:http://docs.sequelizejs.com/manual/tutorial/models-definition.html const User = sequelize.define('user', { firstName: { type: Sequelize.STRING }, lastName: { type: Sequelize.STRING }, }, { // 省略 createdAt 和 updateAt timestamps: false }); // 第一次没有表的时候需要同步来创建 // http://docs.sequelizejs.com/manual/tutorial/instances.html // 官方还有两种额外的做法,一种是先build一个实例,然后save(),一种是直接create sequelize.sync({ force: true }).then(() => { return User.create({ firstName: 'John', lastName: 'Hancock' }) }).then(() => { return User.find({ where: { firstName: 'John' } }) }).then(console.log)
sequelize-cli 的安装和使用
http://docs.sequelizejs.com/manual/tutorial/migrations.html#the-cli
$ npm i sequelize-cli -g $ sequelize init $ sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string
















