hussainb
hussainb

Reputation: 1296

sails.js beforeCreate method receives only the model properties on which required is set to true

This is a model in sails.js.

module.exports = {

    attributes: {
        name: {
            type: "string"
        },
        email: {
            type: "email",
            required: true
        },
        password: {
            type: "string"
        }
    },

    beforeCreate: function(values, next) {
        console.log(values); //logs {email:"[email protected]"}
        console.log(values.email);    // logs the email id sent via post
        console.log(values.password);    // logs undefined is required is set to false, If required is set to true, password will log properly.
        next();
    }
};

I am planning to perform some encrypting of the password in the beforeCreate function, Of course I will be requiring the password and can continue with it right now but how to manage this for optional values just in case the need arises?

Upvotes: 3

Views: 1043

Answers (1)

hussainb
hussainb

Reputation: 1296

I found the reason for the above issue, In my controller, I was doing a create record but the record I was creating contained only one field, i.e the email see below:

Users.create({email:req.body.email}).exec(function(err, user){
   // user created
});

The model is directly mapped with the object being inserted into the database, So internally sails removes/ignores the fields which are not present. To not remove these empty fields, you might have to set schema:true in your model.

Upvotes: 1

Related Questions