lalitb
lalitb

Reputation: 113

Restrict mongoose field values

I'm trying to create:

var mongoose = require('mongoose');

var FeelingSchema = new mongoose.Schema({
    userId: String,
    feelingDate: Date,
    feelingTimeOfDay: String,
    feelingValue: String
  }
);

How do I restrict the value of the field feelingValue to a limited set, say ['happy', 'angry', 'shocked']

I'm using version 3.8.23 of mongoose

Upvotes: 11

Views: 8949

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

You can constrain a string field to a set of enumerated values with the enum attribute in the schema definition:

var FeelingSchema = new mongoose.Schema({
    userId: String,
    feelingDate: Date,
    feelingTimeOfDay: String,
    feelingValue: { type: String, enum: ['happy', 'angry', 'shocked'] }
  }
);

Upvotes: 45

Related Questions