node.js - Mongoose 自定义验证失败

标签 node.js mongodb mongoose

在我的应用程序中,我尝试在 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')

最佳答案

定义 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');

关于node.js - Mongoose 自定义验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938137/

相关文章:

arrays - $push 在 MongoDb 中不起作用?

javascript - node.js 类型错误 : Object has no method get

node.js - 在单独的函数中进行类型检查在 typescript 中不起作用

mongodb - Node JS MongoDb 查询中的点表示法

ruby-on-rails - Mongoid - 如何获得第二条记录?

javascript - 函数编写者如何调用 getByName 。功能

javascript - 在 nuxtServerInit 操作中使用 axios 进行 http 调用

node.js - 使用 Jest 测试 firebase 函数时的 Flakey 测试

mongodb - Golang revel+mgo - 当结构变量具有小写名称时不返回数据

node.js - Mongoose 一对多