Mongoose 自定义验证器
Mongoose Custom Validators
我有以下架构
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
。
您将错误消息传递给 required
,而不是 enum
。在你的情况下,你应该这样做:
type: {
type: String,
enum: {values: ["Push", "Email"], message: "Type must be Push or Email"},
...
},
我有以下架构
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
。
您将错误消息传递给 required
,而不是 enum
。在你的情况下,你应该这样做:
type: {
type: String,
enum: {values: ["Push", "Email"], message: "Type must be Push or Email"},
...
},