Sequelize(ORM)
// utils/utils.js
const crypto = require('crypto')
// 生成 md5 加密
const MD5 = crypto.createHash('md5')
exports.cryptoMd5 = (str) => MD5.update(str).digest('hex')
// 随机字符串
exports.randomStr = (len = 6) => crypto.randomBytes(len).toString('hex') // 生成 10 位的盐值
// model/User.js
const Sequelize = require('sequelize') // npm i mysql2 sequelize
const { cryptoMd5, randomStr } = require('../utils/utils')
const dataConfig = { user: 'root', password: 'Mysql221503@' }
// 1. 连接数据库
const sequelize = new Sequelize('sequelize_test', dataConfig.user, dataConfig.password, {
host: 'localhost',
dialect: 'mysql',
operatorsAliases: false,
})
// 2. 定义模型(水果): 会自动处理id, 添加 createdAt, updatedAt
const User = sequelize.define(
'user',
{
id: { // 配置使用 uuid: 自增id不用定义
type: Sequelize.DataTypes.UUID, // 数据类型
defaultValue: Sequelize.DataTypes.UUIDV1, // 默认值
primaryKey: true, // 是否为主键
field: 'id', // 数据库中字段真是名称,默认就是属性名
unique: false, // 是否可重复
autoIncrement: false, // 是否自增, 无值时为 null
},
username: { type: Sequelize.STRING, allowNull: false, },
password: {
type: Sequelize.STRING,
set(pwd) { // Getter Setter
const salt = randomStr(10) // 生成 10 位的盐值
this.setDataValue('password', cryptoMd5(pwd + salt)) // 保存 hash 后的密码
this.setDataValue('salt', salt) // 保存 salt
}
},
salt: { type: Sequelize.STRING, },
age: {
type: Sequelize.INTEGER,
validate: { // 检验
max: { args: 100, msg: '年龄不能大于 100' },
min: { args: 1, msg: '年龄不能小于 1' },
customFunc(val){ // 自定义验证
if(val === 50) throw new Error('年龄不能等于 50')
}
}
},
infoId: { // 外键
type: Sequelize.INTEGER,
field:'info_id',
references: { // 外键 model是对应的模型,key是外键链接的字段
model: Info, // Info: 外键表的模型名
key: 'id', // User(info_id) 是 Info(id) 的外键
}
},
price: { type: Sequelize.FLOAT, allowNull: false, },
stock: { type: Sequelize.INTEGER, defaultValue: 0 },
},
{
timestamps: false, // 避免自动生成时间戳字段: createdAt, updateAt
freezeTableName: true, // 锁定表名
tableName: '自定义表名',
underscore: true, // 蛇形命名(下划线), 默认驼峰
// getterMethods, setterMethods 这个是相当与在存取时都添加了 changeName 这个虚拟字段
getterMethods: {
changeName(){
return this.username+'changeName';
}
},
setterMethods:{
changeName(val){
return this.setDataValue('username', val.slice(0, -1));
}
},
}
)
module.exports = User
// app.js
const Sequelize = require('sequelize')
const User = require('./model/User')
const main = async () => {
// 3. 同步:
await User.sync({ force: true }) // { force: true }: 强制同步, 创建表之前删除已存在的表
// 4. 操作
await User.create({ username: '香蕉', password: '123456' }) // 创建
await User.update( // 更新
{ price: 4.5 },
{ where: { name: '香蕉' } },
)
const Op = Sequelize.Op
await User.findAll({ // 查询
where: {
price: {
[Op.gt]: 2, // 大于 2
[Op.lt]: 5, // 小于 5
}
}
})
}
main()