Mongoose 异步自定义验证无法按预期工作 [英] Mongoose async custom validation not working as expected

查看:52
本文介绍了Mongoose 异步自定义验证无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的架构中,我正在执行大量异步的自定义验证.但是,验证的行为并不像我期望的那样.即使 promise 以false"解决,mongoose 仍会继续验证. 根据 他们的文档,不应该是这种情况.

in my schema, I'm performing a lot of asynchronous, custom validations. However, validation is not behaving as I expect it to behave. Even though promises resolve with "false", mongoose continues validation. According to their documentation, that shouldn't be the case.

示例架构:

    var questSchema = mongoose.Schema({
      questCategory: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        validate: {
          validator: async function (v) {
            await data_verificator.checkIfQuestCategoryExists(v);
          },
          message: (props) => `${props.value} is not a valid quest category id.`,
        },
      },
      fulfillmentPeriod: {
        type: String,
        required: true,
        validate: {
          validator: async function (v) {
            await data_verificator.checkFulfillmentPeriod(this.questCategory, v);
          },
          message: (props) =>
            `${props.value} is an invalid value as it violates the limitations set by the quest category.`,
        },
      },
    })

请注意,这两个架构字段的自定义验证异步发生.questCategory 字段的验证工作得非常好.如果承诺解析为 false,则验证失败.但是,fulfillmentPeriod 字段并非如此.即使 promise 解析为 false,验证也会成功.

Note that the custom validation happens asynchronously for those two schema fields. The validation of the questCategory field works perfectly fine. If the promise resolves to false, validation fails. However, that's not the case for the fulfillmentPeriod field. Even though the promise resolves to false, the validation succeeds.

我不知道为什么会出现这种奇怪的行为.如果我将 fulfillmentPeriod 的验证重写为如下所示,一切都会再次按预期工作.解析为 false 的承诺会导致验证失败.这是为什么?为什么它适用于下面的代码而不适用于我粘贴在上面的初始代码?那是因为我引用了另一个异步验证的架构字段吗?

I am not sure why I get this weird behavior. If I were to rewrite validation of the fulfillmentPeriod to look like the following, everything works as expected again. The promise resolving to false causes the validation to fail. Why is that? Why does it work with below code but not with the initial code I pasted above? Is that because I'm referencing another schema field that is validated asynchronously?

validator: async function (v) {
  const result = await data_verificator.checkFulfillmentPeriod(this.questCategory, v);
  return result;
},

为了以防万一这很重要,checkFulfillmentPeriod 函数看起来像这样:

Just in case this is important, the checkFulfillmentPeriod function looks like this:

const checkFulfillmentPeriod = async function (categoryId, period) {
  const connectionManager = require("../configuration").connectionManager;

  var category = await connectionManager.QuestCategoryModel.findOne({
    _id: categoryId,
    availableFulfillmentPeriods: {
      $elemMatch: {
        period: period,
      },
    },
  });

  if (!category) return false;

  return true;
};

该函数只是检查是否有符合条件的类别.如果是,则返回 true.否则为假.据我了解,问题并非源于此函数,而是与 mongoose 的验证有关.

The function simply checks if there's a category matching the criteria. If so, true is returned. Otherwise false. From what I've found out, the issue doesn't originate in this function but has something to do with mongoose's validation.

checkIfQuestCategoryExists函数看起来完全一样,只是查询设置不同.

The checkIfQuestCategoryExistsfunction looks exactly the same, just with different query settings.

我已经在这个问题上花费了几个小时,此时我再也看不到任何错误了.

I've spent hours on this issue and at this point I just don't see any errors anymore.

如果我能得到任何帮助/建议,我将不胜感激!

推荐答案

你能试试这个代码吗:

var questSchema = mongoose.Schema({
      questCategory: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        validate: {
          validator: async function (v) {
            return await data_verificator.checkIfQuestCategoryExists(v);
          },
          message: (props) => `${props.value} is not a valid quest category id.`,
        },
      },
      fulfillmentPeriod: {
        type: String,
        required: true,
        validate: {
          validator: async function (v) {
            return await data_verificator.checkFulfillmentPeriod(this.questCategory, v);
          },
          message: (props) =>
            `${props.value} is an invalid value as it violates the limitations set by the quest category.`,
        },
      },
    })

这篇关于Mongoose 异步自定义验证无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆