[Mongoose] Async Validators Section

So, mosh teaches a deprecated way of async validation cause i’m getting an error saying isAsync is deprecated and that we should make it a promise which is really confusing to me. Since, i don’t want to learn deprecated information before continuing the course. I’m asking anyone here to show me how to refactor this part below into the new syntax. I looked at the documentation and tried to refactor it myself with no luck.

Deprecated Code

tags: {
    type: Array,
    validate: {
      isAsync: true,
      validator: function (v, callback) {
        setTimeout(() => {
          const result = v && v.length > 0;
          callback(result);
        }, 4000);
      },
      message: "A course should have at least one tag",
    },
  },

Valid Code Documentation:

Try this StackOverflow answer: Mongoose: the isAsync option for custom validators is deprecated.

I solved it this way

tags: {
type: Array,
validate: {
validator: async function (v) {
return await checkTags(v);
},
message: "course shoud have at least one tag"
}
},

And the function

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

    }, 2000);
  }); 
}
2 Likes

The easiest way to solve this issue is to use Promise instead of Async.
This is how I have solved this and it’s working fine

You can also check out this link for further details https://javascript.plainenglish.io/store-clean-data-by-validating-models-with-mongoose-f6453dbdbff9

Happy coding :slight_smile:

4 Likes

You are a life-saver, cheers mate. Thankyou