mongoose自定义validation失败

在我的应用程序中,我试图在mongoose上运行一些自定义的validation,我想要的只是能够确保来自特定用户的评级不应超过一次,我已经尝试了几件事情,并且开始了代码正确返回true和false,但错误不会被触发。 这是我的代码

RatingSchema.path('email').validate(function (email) { var Rating = mongoose.model('Rating'); //console.log('i am being validated') //console.log('stuff: ' + this.email+ this.item) Rating.count({email: this.email, item: this.item},function(err,count){ if(err){ console.log(err); } else{ if(count===0){ //console.log(count) return true; } else { //console.log('Count: in else(failing)'+ count) return false; } } }); },'Item has been already rated by you') 

当定义一个执行asynchronous操作的validation器时 (比如你的Rating.count调用),你的validation器函数需要接受第二个参数,这个参数是你调用的提供true或false结果的callback,因为你不能只返回asynchronous结果。

 RatingSchema.path('email').validate(function (email, respond) { var Rating = mongoose.model('Rating'); Rating.count({email: this.email, item: this.item},function(err,count){ if(err){ console.log(err); } else{ if(count===0){ respond(true); } else { respond(false); } } }); },'Item has been already rated by you');