sails js对数据库的模型验证

Ash*_*ana 3 sails.js

我正在编写一个自定义验证规则来检查传递给我的create函数的"category_id"是否有效.

types: {
  isValidCategoryId: function(id){
    return Category.findOne({id: id}).exec(function(err, user){
      if(err || !user)
        return false;
      else{
        return true;
      }  
  });
 }
},


attributes: {
  category_id : { isValidCategoryId: true, required: true, type: 'string' },
}
Run Code Online (Sandbox Code Playgroud)

我知道我的自定义验证函数应该返回true,但在异步上下文中,这可能不起作用,比如检查DB中的值.

我应该如何编写自定义验证函数以使其正常运行?

Arl*_*son 6

我尝试过particlebanana的解决方案.它没有用,但至少它指出了我正确的方向.

根据文件:

验证规则可以定义为返回要测试的值的简单值或函数(同步和异步).

因此,一个简单的方法是:

attributes: {
    category_id : {
        required: true,
        type: 'string',
        'true': function(cb) {
            Category.findOne({id: this.category_id}).exec(function(err, category){
                return cb(!err && category);
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我只是在这里使用"真正的"验证器,但您当然可以编写自己的验证器来制定更高级的逻辑.这里的关键是您的自定义验证器 不是异步的,但验证规则 可以是.是的,这个术语很混乱.

这是自定义验证器的另一个示例:

attributes: {
    author: {
        required: true,
        type: 'string',
        canPost: function(cb) {
            Author.findOne(this.author).exec(function(err, author) {
                return cb(author);
            });
        }
    }
},
types: {
    canPost: function(id, author) {
        return author && author.canPost();
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这是有道理的.如果没有,请参阅文档.