使用 sequelize init
我生成了一个带有迁移的模型。
在 model.js 中只有每个属性的类型定义,例如
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING
}, {});
在迁移文件中,还有其他选项,例如
...
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING,
},
password: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
...
例如,如果我想让电子邮件独一无二,我会将电子邮件属性更改为:
email: {
type: Sequelize.STRING,
unique: true
},
我的问题是在 model.js 文件中包含这些额外的属性选项是好还是坏的主意,或者只是通过仅保留属性的定义(
types
)来保持简单。
最佳答案
是的,你可以做到,也可以像这样定义值的验证。
因此,您不必每次都在 api call 中查找 email_id
是否已经退出。
email: {
type: Sequelize.STRING(18),
validate: {
isUnique(value, next) {
user.find({
where: { email: value },
attributes: ['id']
}).done((user) => {
if (user)
return next('errors.email.unique');
next();
});
}
}
关于mysql - 数据库模型的元数据应该在模型文件还是迁移文件中定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62428876/