如何在 beforeCreate 中取消在 Sails 中创建记录

How to cancel the creation of a record in Sails in beforeCreate

我知道当您通过创建 URL 将适当的字段传递给 Sails 时,Sails 会自动创建一条记录。创建新记录时,我需要查看该记录是否存在。如果它不存在,我创建它。如果它确实存在,我不应该创建它。我已经成功地检查了记录是否存在,但是如果记录确实存在,我不知道该怎么办。我如何告诉 Sails 不要创建记录?

beforeCreate: function(values, cb) {

  User.findOne({ where: { name: values.name}}).exec(function(err, found) {
    if(found == undefined) console.log("NOT FOUND"); //create the record
    else console.log("FOUND"); //don't create the record
  });

  cb();

}

当 Sails 命中 cb() 时,它会自动创建记录。我该怎么做才能决定是否创建记录?

使用可以停止创建的 beforeValidate 函数代替 beforeCreate 函数 (http://sailsjs.org/#!/documentation/concepts/ORM/Lifecyclecallbacks.html)。

beforeValidation: function(values, next){
 User.findOne({ where: { name: values.name}}).exec(function(err, found) {
    if(found == undefined){
        console.log("NOT FOUND"); //create the record
        next();
    }
    else{ 
       console.log("FOUND"); //don't create the record
       next("Error, already exist");  
    }

    });
} 

为未来的开发者处理这个问题的最好方法是坚持水线验证机制 WLValidationError

beforeCreate: function (values, cb){

    //this is going to throw error 
    var WLValidationError = require('../../node_modules/sails/node_modules/waterline/lib/waterline/error/WLValidationError.js');

    cb(new WLValidationError({
          invalidAttributes: {name:[{message:'Name already existing'}]},
          status: 409
         // message: left for default validation message
        }
      ));
    }