Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define instance methods for models with sails.js

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)

like image 755
Adrien Avatar asked Jul 18 '13 10:07

Adrien


People also ask

How do I interact with every model in sails?

Every model in Sails has a set of methods exposed on it to allow you to interact with the database in a normalized fashion. This is the primary way of interacting with your app's data. Since they usually have to send a query to the database and wait for a response, most model methods are asynchronous.

What happened to instance methods in sails and waterline?

As of Sails v1.0, instance methods have been removed from Sails and Waterline. While instance methods like .save () and .destroy () were sometimes convenient in app code, in Node.js at least, many users found that they led to unintended consequences and design pitfalls. For example, consider an app that manages wedding records.

What is sails JS?

sails.js is an MVC (Model View Controller) web framework for node.js that emulates familiar MVC frameworks like Ruby on Rails. sails.js is based on Express and provides websocket support via socket.io. sails.js provides a set of conventions and default configurations to quickly get a new website project started.

How do I define instance methods with Sequelize?

Sequelize allows you to define instance methods for your model. Any instance method you define in the model can be called from the object returned by Sequelize query methods. There are two ways you can define instance methods with Sequelize: This tutorial will help you learn both ways, starting with adding a prototype function


Video Answer


1 Answers

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
});
like image 128
Adrien Avatar answered Oct 26 '22 19:10

Adrien