Search code examples
mongoosemongoose-schema

Mongoose Custom Validators


I have the following schema

const ReminderSchema = new Schema({
  type: {
    type: String,
    enum: ["Push", "Email"],
    required: [true, "Type must be Push or Email"]
  },
 ...

And here is my code for when I save a new Reminder

new Reminder({
  title: title
})
  .save()
  .then(doc => {
    res.json(doc);
  })
  .catch(err => {
    console.log(err);
    if (err.errors) {
      const error = ValidatorParse(err.errors);
      if (typeof err.errors.type !== "undefined") {
        return res
          .status(400)
          .json({ FieldTypeError: err.errors.type.message });
      } else {
        return res.status(400).json(error);
      }
    } else {
      console.error(err);
      return res.status(500).json({
        message: "Unexpected Error Occured, this is my fault 🤖"
      });
    }
  });

And the console.log(err) prints the following:

{
  message: '`te` is not a valid enum value for path `type`.',
  name: 'ValidatorError',
  properties: {
    validator: [Function (anonymous)],
    message: '`te` is not a valid enum value for path `type`.',
    type: 'enum',
    enumValues: [ 'Push', 'Email' ],
    path: 'type',
    value: 'te'
  },
  kind: 'enum',
  path: 'type',
  value: 'te',
  reason: undefined,
  [Symbol(mongoose:validatorError)]: true
}

I am expecting it to print the custom error message Type must be Push or Email.


Solution

  • You pass your error message to required, not enum. In your case, you should do like this:

    type: {
      type: String,
      enum: {values: ["Push", "Email"], message: "Type must be Push or Email"},
      ...
    },