How to define instance methods for models with sails.js

Adrien picture Adrien · Jul 18, 2013 · Viewed 7.2k times · Source

How can I define functions/instance method for objects in Sails ?

In Waterline doc (https://github.com/balderdashy/waterline) they say:

var User = Waterline.Collection.extend({
...
  attributes: {
    ...
    // You can also define instance methods here
    fullName: function() {
      return this.firstName + ' ' + this.lastName
    }
  },
}

But when I try do define an instance method in attributes in a model in Sails, the function is not added to the object. Am I doing something wrong ?

Environment: Sails (v0.8.94), Node (v0.8.16)

Answer

Adrien picture Adrien · Jul 18, 2013

You can define instance methods in models with sails 0.9.0 like this:

module.exports = {
  attributes: {     
    name: {
      type: 'STRING',
      defaultsTo: 'zooname'
    },
    instanceMethod: function(){
      // your code
    }
  }
};

Usage example:

ClientHit.findOne({}).exec(function(err, model){
  model.instanceMethod(); //use your instance method
});