1、模型定义
(1)模型定义
type:必选参数,列的数据类型
allowNull:可选参数,默认为true,对应mysql中是否允许该列为空
defaultValue:可选参数,默认为null,对应mysql中该列的默认值
unique:可选参数,默认为false,标记该列是否唯一,如果设置为ture,会为该列创建一个唯一索引
primaryKey:可选参数,默认为false,标记该列是否为主键
autoIncrement:可选参数,默认为false,该列是否自增,一般和主键联用
comment:可选参数,默认为null,列的注释,v5版本中会将comment字段同步的mysql中的注
(2)特殊用法
对属性进行验证:
const ITEM_TYPES = {
REWARD: 'reward',
MEDAL: 'medal',
};
item_type: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isIn: {
args: [_.values(ITEM_TYPES)],
msg: '不合法的 item_type',
},
notEmpty: true,
},
},
模型验证,允许您为模型的每个属性指定格式/内容/继承验证
。
验证将自动运行在创建,更新和保存。 您也可以调用validate()
手动验证一个实例。
const ValidateMe = sequelize.define('foo', {
foo: {
type: Sequelize.STRING,
validate: {
is: ["^[a-z]+$",'i'], // will only allow letters
is: /^[a-z]+$/i, // same as the previous example using real RegExp
not: ["[a-z]",'i'], // will not allow letters
isEmail: true, // checks for poem format (foo@bar.com)
isUrl: true, // checks for url format (http://foo.com)
isIP: true, // checks for IPv4 (129.89.23.1) or IPv6 format
isIPv4: true, // checks for IPv4 (129.89.23.1)
isIPv6: true, // checks for IPv6 format
isAlpha: true, // will only allow letters
isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail
isNumeric: true, // will only allow numbers
isInt: true, // checks for valid integers
isFloat: true, // checks for valid floating point numbers
isDecimal: true, // checks for any numbers
isLowercase: true, // checks for lowercase
isUppercase: true, // checks for uppercase
notNull: true, // won't allow null
isNull: true, // only allows null
notEmpty: true, // don't allow empty strings
equals: 'specific value', // only allow a specific value
contains: 'foo', // force specific substrings
notIn: [['foo', 'bar']], // check the value is not one of these
**isIn: [['foo', 'bar']], // check the value is one of these
notContains: 'bar', // don't allow specific substrings
len: [2,10], // only allow values with length between 2 and 10
isUUID: 4, // only allow uuids
isDate: true, // only allow date strings
isAfter: "2011-11-05", // only allow date strings after a specific date
isBefore: "2011-11-05", // only allow date strings before a specific date
max: 23, // only allow values <= 23
min: 23, // only allow values >= 23
isCreditCard: true, // check for valid credit card numbers
// custom validations are also possible:
isEven(value) {
if (parseInt(value) % 2 != 0) {
throw new Error('Only even values are allowed!')
// we also are in the model's context here, so this.otherField
// would get the value of otherField if it existed
}
}
}
}
});
设置虚拟字段
fullName: {
type: Sequelize.VIRTUAL,
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
throw new Error('不要尝试设置 `fullName` 的值!');
}
}
获取器
const User = sequelize.define('user', {
// 假设我们想要以大写形式查看每个用户名,
// 即使它们在数据库本身中不一定是大写的
username: {
type: DataTypes.STRING,
get() {
const rawValue = this.getDataValue(username);
return rawValue ? rawValue.toUpperCase() : null;
}
}
});
设置器
const User = sequelize.define('user', {
username: DataTypes.STRING,
password: {
type: DataTypes.STRING,
set(value) {
// 在数据库中以明文形式存储密码是很糟糕的.
// 使用适当的哈希函数来加密哈希值更好.
this.setDataValue('password', hash(value));
}
}
});
组合获取器和设置器
const { gzipSync, gunzipSync } = require('zlib');
const Post = sequelize.define('post', {
content: {
type: DataTypes.TEXT,
get() {
const storedValue = this.getDataValue('content');
const gzippedBuffer = Buffer.from(storedValue, 'base64');
const unzippedBuffer = gunzipSync(gzippedBuffer);
return unzippedBuffer.toString();
},
set(value) {
const gzippedBuffer = gzipSync(value);
this.setDataValue('content', gzippedBuffer.toString('base64'));
}
}
});
注:Sequelize 提供 getDataValue 方法的原因:获取存在数据库的真实的值。
Sequelize 在将数据发送到数据库之前自动调用了设置器,setDataValue设置value值
get()在真实的值做处理,不改变真实的值
set()改变真实的值
学习链接:https://blog.csdn.net/njweiyukun/article/details/103267027
https://www.cnblogs.com/dongfang159/p/7463604.html
https://www.cnblogs.com/goloving/p/13504105.html