I know that Sails automatically creates a record when you pass it the appropriate fields through the create URL. When a new record created, I need to see if the record exists or not. If it doesn't exist, I create it. If it does exist, I should not create it. I have successfully checked to see if the record exists or not, but I'm confused on what to do if the record does exist. How do I tell Sails to not create the record?
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();
}
When Sails hits the cb()
it automatically creates the record. How do I make it so that I decide whether or not to create the record?
Instead of beforeCreate function use the beforeValidate function that can stop the creation (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");
}
});
}
The best way to handle this for the future devs, is to stick with the validation mechanism by waterline 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
}
));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With