How to create “calculated” fields in the Waterline / Sails.js model?

This is my User.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;
        }
    }
  };

I want to use some attribute that is "pre" designed for the model. My solution was to introduce attr in the toJSON () function, but in the views I should use:

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

Is there a way to create an attribute or some methods for the user? How:

module.exports = {

       attributes: {

        name: {
            type: 'string',
            required: true,
            minLength: 3,
            maxLength: 30
        },
        myPersonalAttribute: function(){
           return "Value"   
        }
}
+4
source share
2 answers

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

+2
source
module.exports = {

    attributes: {

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

        myPersonalAttribute: function() {
            return "Value"
        },

        toJSON: function() {
            var obj = this.toObject()
            obj.myPersonalAttribute = this.myPersonalAttribute()
            return obj
        }
    }
}
0

All Articles