Difference between validate and validateSync in mongoose

Viewed 113

I'm looking at mongoose doc, but not clear enough about validate() and validateSync(), i want to know difference between these 2 methods.

1 Answers

validate() returns a promise of void. So you can't hold the result on a variable like this

const result = await course.validate() // can't hold

to handle the validation error you may need to use validate method with a callback.

course.validate((err) => {
   if (err) handleError(err);
   else // validation passed
})

on the other hand validateSync() Executes registered validation rules (skipping asynchronous validators) for this document. It returns ValidationError if there are errors during validation, or undefined if there is no error.

const err = course.validateSync();
if (err) {
  handleError(err);
} else {
  // validation passed
}

***Note: This method is useful if you need synchronous validation.

Related