【发布时间】:2017-09-09 08:00:29
【问题描述】:
在尝试验证在 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;
}
}
}
});
我想在endingDate::validate 函数中访问修改后的文档值(“this”),以确保每个修改后的文档的结束日期大于开始日期。
即使在使用 pre-hook(用于 update 和 updateMany,如下所示)时,我仍然找不到任何方法来访问修改后的文档值以在设置 multi 时(或调用 updateMany 时)执行我的检查。
BusinessesSchema.pre('update', function(next) {
this.options.runValidators = true;
this.options.context = 'query';
next();
});
BusinessesSchema.pre('updateMany', function(next) {
this.options.runValidators = true;
this.options.context = 'query';
next();
});
我可能错过了一些东西,非常感谢这里的帮助。
【问题讨论】:
标签: node.js validation mongoose schema this