Node.js 如何让updatemany在每个修改过的文档上验证mongoose模式?

Node.js 如何让updatemany在每个修改过的文档上验证mongoose模式?,node.js,validation,mongoose,schema,this,Node.js,Validation,Mongoose,Schema,This,我在尝试验证Model::updateMany(或update+mutli:true)请求中修改的文档的模式时遇到了mongoose模式验证问题。 我得到了下面的模式: var BusinessesSchema = new Schema({ label: { type: String, required: true }, openingDate: { type: Date, required: true },

我在尝试验证Model::updateMany(或update+mutli:true)请求中修改的文档的模式时遇到了mongoose模式验证问题。 我得到了下面的模式:

  var BusinessesSchema = new Schema({
    label: {
      type: String,
      required: true
    },
    openingDate: {
      type: Date,
      required: true
    },
    endingDate: {
      type: Date,
      validate: function(value) {
        if (this.constructor.name === 'Query') {
          // Looks like this is a validation for update request
          var doc = null;
          switch (this.op) {
            case 'update':
            case 'updateMany': {
              doc = this._update.$set;
              break;
            }
            case 'findOneAndUpdate': {
              doc = this._update;
              break;
            }
            default:
            // keep null, will throw an error
          }
          return doc.openingDate < value;
        }
        else {
          return this.openingDate < value;
        }
      }
    }
  });

我可能错过了什么,非常感谢您的帮助。

不行。使用
updateMany
可以做的最好的事情是从
中捕获查询上下文,并分析更新。大概是这样的:

Schema.pre('updateMany', function (next) {
    const update = this.getUpdate();
    if (update.$set && update.$set && !validateUpdate(update.$set)) {
        throw new Error('Invalid Update');
    }
    next();
});
如果要在更新之前使用
保存
挂钩对生成的文档进行验证,可以使用光标:

Schema.pre('save', function(next) {
    if (!validDoc(this)) {
        throw new Error('Invalid Doc');
    }
    next();
}
Schema.statics.updateManyWithValidation = async function(criteria, update) {
        const cursor = Model.find(criteria).cursor();
        let doc = null;
        do {
            doc = await cursor.next();
            Object.assign(doc, update);
            await doc.save();
         } while(doc != null);
    }
现在,请记住,这是一个非常昂贵的操作,因为您要获取文档,应用更改,然后单独保存它们

Schema.pre('save', function(next) {
    if (!validDoc(this)) {
        throw new Error('Invalid Doc');
    }
    next();
}
Schema.statics.updateManyWithValidation = async function(criteria, update) {
        const cursor = Model.find(criteria).cursor();
        let doc = null;
        do {
            doc = await cursor.next();
            Object.assign(doc, update);
            await doc.save();
         } while(doc != null);
    }