标签:HERE process http generate use getting mode cal models
安装sequelize
及数据库连接驱动
npm install --save sequelize
$ npm install --save mysql2
创建连接:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'
});
创建Model表:
const Model = Sequelize.Model;
class User extends Model {}
User.init({
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull defaults to true
}
}, {
sequelize,
modelName: 'user'
// options
});
生产数据:
// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
// Now the `users` table in the database corresponds to the model definition
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
// Create a new user
User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => {
console.log("Jane's auto-generated ID:", jane.id);
});
// Delete everyone named "Jane"
User.destroy({
where: {
firstName: "Jane"
}
}).then(() => {
console.log("Done");
});
// Change everyone without a last name to "Doe"
User.update({ lastName: "Doe" }, {
where: {
lastName: null
}
}).then(() => {
console.log("Done");
});
// Find all users
User.findAll().then(users => {
console.log("All users:", JSON.stringify(users, null, 4));
});
对于数据迁移这块,笔者目前实际使用还是不熟练,比如 model
添加了新的字段如何处理、开发环境和生产环境新添加字段或者删除字段怎么处理 ,希望有熟悉的朋友能够指导一二,不胜感激。
参考1:Sequelize 和 MySQL 对照
参考2:Getting started-Sequelize
咨询请加微信:轻撩即可。
全栈项目|小书架|服务器开发-NodeJS 中使用 Sequelize 操作 MySQL数据库
标签:HERE process http generate use getting mode cal models
原文地址:https://www.cnblogs.com/gdragon/p/11871105.html