1、安装
npm install --save sequelize
安装对应的数据库驱动程序:
npm install --save pg pg-hstore # Postgres
npm install --save mysql2
npm install --save mariadb
npm install --save sqlite3
npm install --save tedious # Microsoft SQL Server
2、建立数据库连接
const Sequelize = require('sequelize');
// 数据库配置文件
const sqlConfig = {
host: "localhost",
user: "root",
password: "123456",
database: "sequelize_study",
port: 3306
};
const dbConn = new Sequelize(sqlConfig.database, sqlConfig.user, sqlConfig.password, {
dialect: 'mysql',
host: sqlConfig.host,
port: sqlConfig.port,
timestamp: false,
charset: 'utf8',
define: {
'underscored': true, // 字段以下划线(_)来分割(默认是驼峰命名风格)
'charset': 'utf8'
},
pool: {
max: 10,
min: 0,
idle: 10000
}
});
module.exports = dbConn;
3、定义模型
const Sequelize = require('sequelize');
const dbConn = require('../controllers/dbConn');
// 创建 Model
const userList = dbConn.define('userlist', {
// 指定映射的字段类型,字段名,例如数据库中 user 表中的 username 字段映射成 username
id: {
type: Sequelize.INTEGER(10), // 数据类型
allowNull: false, // 是否为 null
primaryKey: true, // 是否为 主键
autoIncrement: true // 是否 自动填值
},
// 如果不指定 field,会自动映射相同名称的字段
name: {
type: Sequelize.STRING(255),
allowNull: false,
defaultValue: 'admin' // 默认值
},
passward: {
type: Sequelize.STRING(255),
allowNull: false,
defaultValue: '123456' // 默认值
},
department: {
type: Sequelize.STRING(255),
allowNull: false,
defaultValue: '研发部' // 默认值
},
mark: {
type: Sequelize.STRING(255),
allowNull: true,
defaultValue: '初始化数据' // 默认值
}
}, {
// 是否 自动添加数据的 创建、更新 时间戳
timestamps: true,
// 是否 硬删除数据
paranoid: false,
// 访问数据库 user 表
tableName: 'userlist',
// freezeTabelName 为 true 时不会在库中映射表时增加复数表名
// 该选项为 true 时,user 在映射时映射成 user,而为 false 时会映射成users
freezeTableName: true
});
export default userList;
4、参考文档
https://github.com/sequelize/sequelize
https://www.jianshu.com/p/615c9fb068ad
https://juejin.im/post/5d39d5115188257aea108fbe
https://juejin.im/post/5c259cf46fb9a049eb3bff49
5、代码地址
https://github.com/JiannanLv/node-koa-server
随笔小结,不喜勿喷,谢谢。