AlexeyBasov AlexeyBasov - 6 months ago 38
Node.js Question

Mongoose schema validation

in schema i have

email: {
type: String,
required: [true, "Email is required"],
unique: true
}
for validation with "unique" i am create
schema.path('email').validate(function(v){
mongoose.models['User'].findOne({email: this.email}, function(err, user){
if(err){
throw err;
}else{
if(user){
this.invalidate("email", "Email exists!");
}
}
});
}, null);


but i have an error:
this.invalidate is not a function. Who can help me?

Answer

You need to use asynchronous validation:

schema.path('email').validate(function(email, callback) {
  mongoose.models['User'].findOne({ email : mail }, function(err, user) {
    if (err) {
      return callback(false, 'Unable to check for e-mail uniqueness due to database error');
    } else if (user) {
      return callback(false, 'E-mail should be unique');
    } else {
      return callback(true);
    }
  });
});