文档验证器
Mongoose 有几个内置的验证器。
对于你的情况,你可以做这样的事情
const mealSchema = Schema({
_id: Schema.Types.ObjectId,
title: { type: string, required: true },
sauce: {
type: string,
required: function() {
return this.title === "pasta"? true:false ;
}
}
});
如果内置验证器不够用,您可以定义自定义验证器以满足您的需求。
自定义验证是通过传递一个验证函数来声明的。您可以在SchemaType#validate() 中找到有关如何执行此操作的详细说明。
更新验证器
this 是指使用文档验证时正在验证的文档。但是,在运行更新验证器时,正在更新的文档可能不在服务器的内存中,因此默认情况下,this 的值未定义。那么,有什么办法呢?
context 选项可让您将更新验证器中 this 的值设置为基础查询。
在你的情况下,我们可以这样做:
const mealSchema = Schema({
_id: Schema.Types.ObjectId,
title: { type: string, required: true },
sauce: { type: string, required: true }
});
mealSchema.path('sauce').validate(function(value) {
// When running update validators with
// the `context` option set to 'query',
// `this` refers to the query object.
if (this.getUpdate().$set.title==="pasta") {
return true
}else{
return false;
}
});
const meal = db.model('Meal', mealSchema);
const update = { title:'pasta', sauce:false};
// Note the context option
const opts = { runValidators: true, context: 'query' };
meal.updateOne({}, update, opts, function(error) { assert.ok(error.errors['title']); });
不确定这是否能回答您的问题。希望这能为您的最终解决方案增加一些价值。
尚未测试,如果此解决方案需要升级,请提出修改建议。
希望这会有所帮助。