猫鼬异步自定义验证无法正常工作

时间:2020-09-07 20:05:23

标签: javascript node.js mongodb mongoose mongoose-schema

在我的模式中,我正在执行许多异步的自定义验证。但是,验证并不像我期望的那样表现。 即使诺言以“ false”解析,猫鼬也会继续验证。their documentation称,情况并非如此。

示例架构:

    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字段不是这种情况。即使承诺解析为false,验证也会成功。

我不确定为什么会出现这种奇怪的行为。如果我将fulfillmentPeriod的验证重写为如下所示,则一切将再次按预期工作。解析为false的承诺会导致验证失败。这是为什么?为什么它对下面的代码有效,但对我上面粘贴的初始代码无效?那是因为我要引用另一个经过异步验证的架构字段吗?

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

如果这很重要,则checkFulfillmentPeriod函数如下所示:

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。否则为假。据我了解,这个问题并非源于此功能,而是与猫鼬的验证有关。

checkIfQuestCategoryExists函数的外观完全相同,只是查询设置不同。

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

我将不胜感激!

2 个答案:

答案 0 :(得分:3)

您的验证器缺少return语句,因此就像您正在返回Promise<void>一样,这不会使mongo的验证触发。您可以添加return或重写您的函数,但前提是后者会不太优雅。

new Promise( (resolve,reject) => {
  .....
  resolve(true/false);
});

答案 1 :(得分:0)

您可以尝试以下代码吗?

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.`,
        },
      },
    })
相关问题