2016-06-08 180 views
0

架構中,我有貓鼬架構驗證

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

,但我有一個錯誤: this.invalidate不是一個函數。誰能幫我?

回答

0

您需要使用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); 
    } 
    }); 
}); 
+0

感謝,它幫助我)! – MrGabriel