Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between validate and validateSync in mongoose

Tags:

mongoose

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

like image 736
J Nguyen Avatar asked Oct 17 '25 04:10

J Nguyen


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.

like image 160
Zubayer Hossain Avatar answered Oct 19 '25 13:10

Zubayer Hossain