How to undo creating an entry in Sails in beforeCreate

I know that Sails automatically creates an entry when you pass the appropriate fields to it through the creation URL. When a new record is created, I need to see if the record exists or not. If it does not exist, I create it. If it exists, I should not create it. I have successfully checked if the record exists or not, but I am confused about what to do if the record exists. How can I say that Sails did not create a 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 gets in cb(), it automatically creates a record. How can I do this to decide whether to create a record?

+4
source share
2 answers

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");  
    }

    });
} 
+5

- 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
        }
      ));
    }
0

All Articles