我需要为某些特定字段运行验证器而不影响模型验证状态。怎么办呢?
这个上下文是有一个验证钩子,用于验证一个字段(var a = "";var b ="";var c= "";
var str = "ItemID=123&Name=AO Document&Dept=Testvalue";
),但它需要确保(foo
)是可以的。
bar
通过不使用现有的...
bar: {
required: true,
type: Number,
min: 2,
max: 10,
validator: isInteger
}
...
function validateFoo(foo, bar) {
// the code below will throw if bar is not an integer between 2 and 10
...
}
schema.pre('validate', function (next) {
if (/* check if model.bar is valid */) {
if (!validateFoo(model.foo, model.bar)) {
model.invalidate('foo', 'foo is invalid');
}
} else {
model.invalidate('foo', 'foo is invalid because of bar');
}
next();
});
模式验证器来执行此操作将导致WET代码:
bar
答案 0 :(得分:0)
您应该在此处查看“自定义验证器”部分: http://mongoosejs.com/docs/validation.html
这样, bar 验证程序将在预验证挂钩之前运行。
另外,我不明白为什么一个字段的验证会依赖另一个字段。也许,你应该对你打算做什么更加明确。