Mongoose条件要求验证

时间:2014-03-29 15:14:03

标签: validation mongoose

我正在使用mongoose并尝试设置一个自定义验证,告诉该属性是否需要(即非空)如果另一个属性值设置为某个值。我使用下面的代码:

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}{"type":"other"}保存模型,则永远不会执行验证功能,并且"无效"数据被写入数据库。

3 个答案:

答案 0 :(得分:5)

从mongoose 3.9.1开始,您可以将函数传递给架构定义中的required参数。这解决了这个问题。

另请参阅mongoose上的对话:https://github.com/Automattic/mongoose/issues/941

答案 1 :(得分:4)

无论出于何种原因,Mongoose设计师决定,如果字段的值为null,则不应考虑自定义验证,从而使条件必需验证不方便。我发现解决这个问题的最简单方法是使用一个非常独特的默认值,我认为它是"就像null"。

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()
});

完全破解,但到目前为止它对我有用。

答案 2 :(得分:0)

尝试将此验证添加到type属性,然后相应地调整验证。 E.g:

function validator(val) {
  val === 'other' && this.thing === '';
}