AlexeyBasov AlexeyBasov - 2 years ago 203
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
mongoose.models['User'].findOne({email:}, function(err, user){
throw err;
this.invalidate("email", "Email exists!");
}, null);

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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download