【问题标题】:runValidator property not working on upsert on mongodb with mongooserunValidator 属性无法在 mongodb 上使用 mongoose 进行 upsert
【发布时间】: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 的两种方式都不起作用。

【问题讨论】:

    标签: mongodb validation mongoose mongoose-schema


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 1970-01-01
      • 2013-06-23
      • 2012-01-19
      • 2015-09-07
      • 2022-12-04
      • 1970-01-01
      • 2018-03-11
      • 2014-11-03
      相关资源
      最近更新 更多