0
0
MongodbHow-ToBeginner · 3 min read

How to Use Enum in Mongoose Schema for MongoDB

In Mongoose, use the enum option inside a schema field to restrict its values to a specific set. Define the field type and add enum with an array of allowed strings or numbers to enforce this constraint.
📐

Syntax

The enum option in a Mongoose schema defines a list of allowed values for a field. It works with String or Number types. When you set enum, Mongoose will only accept values from the specified list for that field.

Example parts:

  • type: The data type of the field (usually String or Number).
  • enum: An array of allowed values.
javascript
const schema = new mongoose.Schema({
  status: {
    type: String,
    enum: ['pending', 'active', 'completed']
  }
});
💻

Example

This example shows how to create a Mongoose schema with an enum field called status. It only allows the values 'pending', 'active', or 'completed'. Trying to save a different value will cause an error.

javascript
const mongoose = require('mongoose');

const taskSchema = new mongoose.Schema({
  name: String,
  status: {
    type: String,
    enum: ['pending', 'active', 'completed'],
    required: true
  }
});

const Task = mongoose.model('Task', taskSchema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  // Valid document
  const task1 = new Task({ name: 'Task 1', status: 'active' });
  await task1.save();

  // Invalid document - will throw validation error
  const task2 = new Task({ name: 'Task 2', status: 'done' });
  try {
    await task2.save();
  } catch (err) {
    console.log('Validation Error:', err.message);
  }

  await mongoose.disconnect();
}

run();
Output
Validation Error: Task validation failed: status: `done` is not a valid enum value for path `status`.
⚠️

Common Pitfalls

Common mistakes when using enum in Mongoose include:

  • Not specifying the type along with enum, which can cause the enum to be ignored.
  • Using values in the enum array that don't match the data type of the field.
  • Trying to save a value not listed in the enum, which triggers a validation error.
  • Forgetting to handle validation errors when saving documents.
javascript
const wrongSchema = new mongoose.Schema({
  status: {
    enum: ['pending', 'active', 'completed'] // Missing type: String
  }
});

const correctSchema = new mongoose.Schema({
  status: {
    type: String,
    enum: ['pending', 'active', 'completed']
  }
});
📊

Quick Reference

OptionDescriptionExample
typeData type of the field`type: String`
enumArray of allowed values`enum: ['small', 'medium', 'large']`
requiredMakes field mandatory`required: true`
defaultSets default value`default: 'pending'`

Key Takeaways

Use the enum option with a type to restrict field values in Mongoose schemas.
Enum values must match the field's data type exactly.
Saving a value outside the enum list causes a validation error.
Always handle validation errors when saving documents with enum fields.
Specify enum as an array of allowed strings or numbers.