ArticleZip > Mongoose Schema Property With Specific Values

Mongoose Schema Property With Specific Values

When working with Mongoose and designing your database schemas, you may come across the need to define a property that should only accept specific values. This is a common requirement when you want to restrict the input to a predefined set of options. In Mongoose, you can achieve this by using the `enum` property type.

The `enum` property type in Mongoose allows you to specify an array of allowed values for a particular field in your schema. When a document is created or updated, Mongoose will ensure that the value provided for that field matches one of the predefined options.

To define a schema property with specific values using the `enum` type, you can do so as follows:

Javascript

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    category: {
        type: String,
        enum: ['Electronics', 'Clothing', 'Books', 'Toys']
    }
});

const Product = mongoose.model('Product', productSchema);

// Example of creating a new product document
const newProduct = new Product({
    name: 'Laptop',
    category: 'Electronics'
});

newProduct.save()
    .then((product) => {
        console.log('Product saved successfully:', product);
    })
    .catch((error) => {
        console.error('Error saving product:', error);
    });

In this example, we have a `productSchema` with two properties: `name` and `category`. The `category` property is defined with the `enum` constraint, specifying that it can only have one of the four values: 'Electronics', 'Clothing', 'Books', or 'Toys'.

When creating a new product document using this schema, if you try to set the `category` field to a value other than the specified options, Mongoose will throw a validation error.

Using the `enum` property type not only ensures data integrity in your database but also provides a clear structure for your application's data model. It helps prevent invalid data from being stored and maintains consistency across your documents.

Remember that the `enum` constraint is case-sensitive, so the values provided when creating or updating a document must exactly match one of the options specified in the `enum` array.

By incorporating specific values using the `enum` type in your Mongoose schemas, you can enforce constraints on your data and design robust schemas that accurately represent your application's domain model. This approach enhances the reliability and maintainability of your database operations, leading to a more structured and organized codebase.

×