mongoose - Mongoose 自定义验证器
问题描述
我有以下架构
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"},
...
},
推荐阅读
- python - 在 PyQt 的第二个线程中打开子对话框的正确方法是什么?
- java - 如何为给定的 maven 或 gradle 项目生成已弃用的库列表?
- c# - 使用派生类时如何使用 Fluent Assertion Should().BeEquivalentTo() 检查等价性
- tensorflow - 在 tensorflow 中显示 CUDA 运行时版本
- java - 从 java 8 迁移到 11 - jaxws-rt
- python - 查找矩阵的乘积时出错
- php - 教义固定装置 ManyToOne - Faker 不加载
- amazon-web-services - 有人可以在本地(使用私有地址)连接/发现我的 AWS 服务/实例吗?
- python - 词干地理词
- batch-file - 在打开 Notepad++ 的文件夹中的 Notepad++ 中打开批处理文件