问题
Using sequelize init
I generated a model with a migration.
Inside model.js there is only the definition of the type of each attribute, e.g.
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING
}, {});
In migration file, there are additional options e.g.
...
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
}
});
},
...
If for example I want to make email unique, I would change the email attribute to:
email: {
type: Sequelize.STRING,
unique: true
},
My question is whether is a good or bad idea to also include those extra options of attributes inside model.js file or just keep it simple by keeping only the definitions of the attributes (the types
).
回答1:
yes , you can do it and also you can define validation for the value like this .
so , you don't have to find every time that email_id
is already exits or not in api call .
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();
});
}
}
来源:https://stackoverflow.com/questions/62428876/database-models-meta-data-should-be-defined-in-models-file-or-migration-file