猫鼬自定义验证器

时间:2020-01-03 00:46:28

标签: mongoose mongoose-schema

我有以下模式

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

这是我保存新的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 ?"
      });
    }
  });

console.log(err)打印以下内容:

{
  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
}

我希望它能打印自定义错误消息Type must be Push or Email

1 个答案:

答案 0 :(得分:2)

您将错误消息传递给required,而不是enum。对于您的情况,您应该这样做:

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