在我的应用程序中,我试图在mongoose上运行一些自定义验证,我想要的是能够确保来自特定用户的评级不应超过一次,我尝试过几件事,并且代码以正确返回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')
答案 0 :(得分:1)
定义执行异步操作的validator(如Rating.count
调用)时,验证器函数需要接受第二个参数,该参数是您调用以提供true或false结果的回调因为你不能只返回异步结果。
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');