Mongoose条件要求验证

spi*_*rit 8 validation mongoose

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

thing: {
type: String,
validate: [
    function validator(val) {
        return this.type === 'other' && val === '';
    }, '{PATH} is required'
]}
Run Code Online (Sandbox Code Playgroud)
  • 如果我保存模型{"type":"other", "thing":""}失败正确.
  • 如果我保存的模型{"type":"other", "thing": undefined}{"type":"other", "thing": null}{"type":"other"}将验证功能永远不会执行,而"无效"的数据被写入到数据库.

Ron*_*len 6

从猫鼬3.9.1开始,您可以将函数传递给required模式定义中的参数。这样就解决了这个问题。

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


blo*_*ilk 5

无论出于何种原因,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()
});
Run Code Online (Sandbox Code Playgroud)

一个完整的黑客,但到目前为止它对我有用。