Reputation: 1202
In my application I am trying to run some custom validations on mongoose, all I want is to be able to make sure that ratings from a particular user should not exceed more than once, I have tried a couple of things, and the code to begin with return true and false correctly but the error is not triggered. Here is my code
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')
Upvotes: 1
Views: 78
Reputation: 312095
When defining a validator that performs an asynchronous operation (like your Rating.count
call), your validator function needs to accept a second parameter which is a callback that you call to provide the true or false result as you can't just return async results.
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');
Upvotes: 1