我知道当你通过创建URL传递适当的字段时,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()
时,它会自动创建记录。如何制作以便我决定是否创建记录?
答案 0 :(得分:5)
而不是beforeCreate函数使用可以停止创建的beforeValidate函数(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");
}
});
}
答案 1 :(得分:1)
为未来开发人员处理此问题的最佳方法是通过水线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
}
));
}