PaoYa Chien
PaoYa Chien

Reputation: 33

Logic of beforeValidate() in sails.js

I am new to sails.js, and after some works I find beforeValidate() hard to use.

I have a model User with just 2 attributes nickname and age. Both attributes are marked as required so sails will check the validation. When creating an user, if the client does not specify its nickname, I would like to assign a random nickname to it, as following:

beforeValidate: function(user, next){
    if (!user.nickname) user.nickname = randomString(5);
    next();
}

This assigning should be applied before sails validates the required tag of nickname, so the beforeValidate() seems to be the only reasonable place to do it. However, when I want to update an user's age like:

User.update(user.id, {age: 40});

It will also trigger beforeValidate() and, sadly, a new nickname will be assigned and replace the origin one, since the parameter user in beforeValidate() now is {age: 40}.

What I expect is that the parameter user in beforeValidate(user, callback) should be updated user, the combination of both changed and unchanged attributes (e.g. user with old id, old nickname and new age), instead of only changed attributes that I specify in User.update() (e.g. only {age: 40}).

Do I misunderstand something?

Upvotes: 0

Views: 947

Answers (1)

Ranjan
Ranjan

Reputation: 448

While calling create() all the values required to add a new record get passed to beforeValidate. Whereas while calling update() only the values that are getting updated are passed to beforeValidate. This is the reason you are getting user.nickname as empty value.

Refer to the docs at http://sailsjs.org/documentation/concepts/models-and-orm/lifecycle-callbacks.

Callbacks on create

beforeValidate: fn(values, cb)

Callbacks on update

beforeValidate: fn(valuesToUpdate, cb)

Upvotes: 1

Related Questions