我的模型有一个验证器函数,用于检查ForeignKey。
下面是我的locationId属性的模型代码。
locationId: {
type: mongoose.SchemaTypes.ObjectId,
required: true,
validate: {
isAsync: true,
validator: function(v) {
return FKHelper(mongoose.model('Account_LocationMapping'), v);
},
message: `LocationId doesn't exist`
}
}
FK Helper
module.exports = (model, id) => {
return new Promise((resolve, reject) => {
model.findOne({ _id: id }, (err, result) => {
if (result) {
return resolve(true);
} else
return reject(
new Error(`FK Constraint 'checkObjectsExists' for '${id.toString()}' failed`)
);
});
});
};
我的追加销售查询:
updateOne: {
filter: {
accountId: req.account
},
update: {
$set: { locationId: req.location },
//runValidator:true -> tried setting the validator property inside update.
},
upsert: true,
runValidators: true
}
我尝试设置runValidator:true的两种方式都不起作用。
我认为问题就在这里:When using update validators, required validators only fail when you try to explicitly $unset the key.
从文档中:https://mongoosejs.com/docs/validation.html#update-验证器仅在更新的路径上运行