node.jsmongoose

Node.js mongoose schema validation - when using enum, is it case sensitive?


when creating a mongoose schema, and using enum in order to validate the values, is it case sensitive?

As in:

const mySchema = new Schema({
  animal: {
    type: String,
    enum: ['cat', 'dog']
  }
});
const myModel = db.model('animal', mySchema);

const animal1 = new myModel({
  animal: 'CAT'
});

Will animal1 be saved or rejected?

Thanks in advance!


Solution

  • Mongoose has several inbuilt validators. Strings have enum as one of the validators. So enum creates a validator and checks if the value is given in an array & these are case sensitive so it will throw validation error, so you can use .toLowerCase() while saving the doc.