Scott Switzer
Scott Switzer

Reputation: 1074

Mongoose asynchronous schema validation is not working

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.

Upvotes: 6

Views: 3405

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

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

Upvotes: 9

Related Questions