Marcelo Boeira Marcelo Boeira - 10 days ago 5
Javascript Question

How to create 'calculated' fields at Waterline/Sails.js Model?

This is my Users.model:

module.exports = {

attributes: {

name: {
type: 'string',
required: true,
minLength: 3,
maxLength: 30
},

username: {
type: 'string',
required: true,
},

toJSON: function() {
var obj = this.toObject();
obj.link = sails.config.globals.baseUrl + sails.config.routes.user + obj.id;
return obj;
}
}
};


What I want is to use some attribute that is 'pre' calculated at the model.
My solution was to inject the attr at the toJSON() function, but at the views I have to use:

<%= users.toJSON().link %>


There's a way to create a attribute or some methods to the user? Like:

module.exports = {

attributes: {

name: {
type: 'string',
required: true,
minLength: 3,
maxLength: 30
},
myPersonalAttribute: function(){
return "Value"
}
}

Answer

You can use attribute methods to return derived values. See my response to your github issue here: https://github.com/balderdashy/waterline/issues/626#issuecomment-54192398

Comments