Inherit attributes and methods of Sails.js Models

Yeah, now I am working on an interesting Node.js project where I am using Neo4j as Graph database with Sails framework. Neo4j is very new in the market, thus there is very little good DB libraries and adapters available for Sails framework. So, I decide to write some custom model methods (using an active record pattern) in the model. The methods are required throughout all the model classes. So, I had to come with a Base Model class concept which will be extended by all other model classes. It’s a Sails framework, you have to do it differently in order to inherit as well as extends from the base class.
One easy way to do this just include the methods in all the model classes like a dumb. Or, you can add all the methods globally using config/models.js like as below:

// config/models.js
module.exports.models = {
  sayHello: function() {

Basically, this sayHello method will be available in all of your model classes. But, I wanted to do it in a bit cleaner way. I extended it by merge() method of lodash library. Here is my code.

I put my base class in models directory

module.exports = {
   sayHello: function() {

And, then the User class looks like below…

var baseModel  = require('./BaseModel'),
    _          = require('lodash');
module.exports = _.merge({}, baseModel, {
//User model implmentation

Done, sayHello method is now available in the User model. One thing is to mention that the first parameter of merge method should be {} (empty) object so that it can’t modify the baseModel. If you put the baseModel as the first parameter like _.merge(BaseModel, {…} then _.merge will modify it.

Btw, don’t forget to include lodash npm package in your project. Just type following line in your project root…

npm install lodash --save

You can also inherit attributes the above way…..


Eftakhairul Islam

Hi, I'm Eftakhairul Islam, a passionate Software Engineer, Hacker and Open Source Enthusiast. I enjoy writing about technical things, work in a couple of startup as a technical advisor and in my spare time, I contribute a lot of open source projects.


Leave a Reply

Your email address will not be published. Required fields are marked *


Read previous post:
Write a View Helper in Laravel 5 with best practices

In my last blog post I talked about deploying Laravel 5 application in a shared hosting. Still I am working...