Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose asynchronous schema validation is not working

Tags:

mongoose

I have the following code which validates my "timezone" field:

orgSchema.path('timezone').validate(function(value) {
  return Timezone.findOne({_id: value}, "_id", function (err, timezone) { return false; });
}, "Please provide a valid timezone");

The field is always passing, even when I add a "return false" in the innermost function. I know that I am missing a callback somewhere - I would appreciate some help.

like image 226
Scott Switzer Avatar asked Jan 11 '13 04:01

Scott Switzer


1 Answers

An asynchronous validator needs to accept a second parameter that's the callback it must call to deliver the boolean result of the validation.

orgSchema.path('timezone').validate(function(value, callback) {
  return Timezone.findOne({_id: value}, "_id", function (err, timezone) { 
    callback(timezone != null);
  });
}, "Please provide a valid timezone");
like image 163
JohnnyHK Avatar answered Jan 02 '23 22:01

JohnnyHK