runValidator 属性无法在 mongodb 上使用 mongoose 进行 upsert

Posted

技术标签:

【中文标题】runValidator 属性无法在 mongodb 上使用 mongoose 进行 upsert【英文标题】:runValidator property not working on upsert on mongodb with mongoose 【发布时间】:2020-08-02 12:22:34 【问题描述】:

我的模型有一个验证器函数,用于检查 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 助手

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`)
                );
        );
    );
;

我的 upsert 查询:

 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 的两种方式都不起作用。

【问题讨论】:

【参考方案1】:

我相信问题就在这里:When using update validators, required validators only fail when you try to explicitly $unset the key.

来自文档:https://mongoosejs.com/docs/validation.html#update-validators-only-run-on-updated-paths

【讨论】:

以上是关于runValidator 属性无法在 mongodb 上使用 mongoose 进行 upsert的主要内容,如果未能解决你的问题,请参考以下文章