Validation Mongoose条件必需验证
我正在使用mongoose并试图设置一个自定义验证,该验证告诉属性如果另一个属性值被设置为某个值,则该属性应该是必需的(即不是空的)。我正在使用下面的代码:Validation Mongoose条件必需验证,validation,mongoose,Validation,Mongoose,我正在使用mongoose并试图设置一个自定义验证,该验证告诉属性如果另一个属性值被设置为某个值,则该属性应该是必需的(即不是空的)。我正在使用下面的代码: thing: { type: String, validate: [ function validator(val) { return this.type === 'other' && val === ''; }, '{PATH} is required' ]} 如果我用{“type”:“
thing: {
type: String,
validate: [
function validator(val) {
return this.type === 'other' && val === '';
}, '{PATH} is required'
]}
- 如果我用
保存一个模型,它会正确地失败李>{“type”:“other”,“thing”:“}
- 如果我用
或{“type”:“other”,“thing”:undefined}
或{“type”:“other”,“thing”:null}
保存模型,则验证函数永远不会执行,“invalid”数据会写入数据库{“type”:“other”}
类型
属性,然后相应地调整验证。例如:
function validator(val) {
val === 'other' && this.thing === '';
}
无论出于何种原因,Mongoose设计者决定,如果字段的值为
null
,则不应考虑自定义验证,这使得有条件的必需验证变得不方便。我发现的最简单的方法是使用一个非常独特的默认值,我认为它是“NULL”。
一个完整的破解,但到目前为止它对我有效。从mongoose 3.9.1开始,您可以将一个函数传递给模式定义中所需的
参数。这就解决了这个问题
另请参见mongoose上的对话:这是mongoose 3.9.1之前的唯一解决方案
var LIKE_NULL = '13d2aeca-54e8-4d37-9127-6459331ed76d';
var conditionalRequire = {
validator: function (value) {
return this.type === 'other' && val === LIKE_NULL;
},
msg: 'Some message',
};
var Model = mongoose.Schema({
type: { type: String },
someField: { type: String, default: LIKE_NULL, validate: conditionalRequire },
});
// Under no condition should the "like null" value actually get persisted
Model.pre("save", function (next) {
if (this.someField == LIKE_NULL) this.someField = null;
next()
});