When creating models using Sequelize sometimes we want to restrict the values used for certain fields to the values available on an enum or object, this way we ensure we can only insert specific values in some columns.
We will create a basic model with some fields using an enum or object values for specified allowed values
const userAvailableStatus = {
active: "active",
suspended: "suspended",
disabled: "disabled",
}
enum userSteps {
ACTIVATE_ACCOUNT = "activateAccount",
INITIAL_INFORMATION = "initialInformation",
INVITE_USERS = "inviteUsers",
}
const User = sequelize.define('User', {
// Model attributes are defined here
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING
},
password: {
type: DataTypes.STRING
},
// We set status to type ENUM and we set that enum values to the userAvailableStatus object values
status: {
type: DataTypes.ENUM(...Object.values(userAvailableStatus))
},
// We set step to type ENUM and we set that enum values to the userSteps enum values
step: {
type: DataTypes.ENUM(...Object.values(userSteps))
},
}, {
// Other model options go here
});
now when we try to save or update a User in our database if we specify a value for status or step that is not in the object or enum, we will get an error