Home > Software design >  Async custom validators mongoose
Async custom validators mongoose

Time:09-26

I'm trying to do some async custom validations in [email protected] `

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

`

This is to check whether the given input has atleast one value in it's array. But I am not getting validated properly. Reffered Mongoose: the isAsync option for custom validators is deprecated. Can anyone help?

CodePudding user response:

Have you tried to call the validateTags to see what it returns? Aswer: undefined and also it returns immediately, it does not wait for the timeout to fire.

The setTimeout with return does not work the way you think.

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

Try this instead:

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