Enum is an inbuilt validator in mongoose. It helps in restricting the possible values of a field to a list of values. Enums come in handy when we already know all the possible values for the field. The field can take one value out of a small set of predefined values.
Example
Imagine we need to build a schema for an online clothing website to store information about all its products. The product schema can contain fields such as the name of the product, brief description, price, quantity in stock, size, etc. A field like size can only take specific values like XS, M, XXL, etc. To enforce this we can use enum from mongoose.
const productSchema = new mongoose.Schema({
name: {
type: String
},
desc:{
type: String
},
price:{
type: Number
},
stock:{
type: Number
},
size:{
type: String
enum: ['XS','S','M','XL','XXL'...]
}
}, { timestamps: true }
)
I hope this article gave you a brief idea about what, why, and how of enum.
Top comments (0)