Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"   
        }
}
like image 319
Marcelo Boeira Avatar asked Oct 31 '22 17:10

Marcelo Boeira


1 Answers

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

like image 123
Travis Webb Avatar answered Nov 12 '22 13:11

Travis Webb