DEV Community

Mitanshi Kshatriya
Mitanshi Kshatriya

Posted on • Edited on

2

Enum: Restrict mongoose fields to a list of values

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 }
)
Enter fullscreen mode Exit fullscreen mode

I hope this article gave you a brief idea about what, why, and how of enum.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay