异步自定义验证器mongoose

hrysbysz  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(204)

我正在mongoose@6.6.1中尝试进行一些异步自定义验证

const courseSchema = new mongoose.Schema({
  tags: {
    type: Array,
    validate: {
      validator: async function (v) {
        return await validateTags(v);
      },
      message: "A Course should have atleast one tags.",
    },
  }
});

const validateTags = async (v) => {
  setTimeout(() => {
    return v && v.length > 0;
  }, 2000);
};

`
这是为了检查给定的输入在它的数组中是否至少有一个值。但是我没有得到正确的验证。参考Mongoose: the isAsync option for custom validators is deprecated。有人能帮忙吗?

sg24os4d

sg24os4d1#

您是否尝试过调用validateTags以查看它返回的内容?Aswer:undefined,并且立即返回,它不等待超时触发。
setTimeoutreturn并不像你想的那样工作。

const validateTags = async (v) => {
  setTimeout(() => {
    // the result of the line bellow is returned to the caller of this function
    // and that is the setTimeout not the validateTags !!!
    return v && v.length > 0;
  }, 2000);
};

请尝试以下操作:

const validateTags = async (v) => {
  return new Promise(function(resolve, reject){
      setTimeout(() => {
        resolve(v && v.length > 0);
      }, 2000);
  });
};

相关问题