How to add an instance method in Sequelize model

Viewed 6557

I would like to add an instance method to Sequelize User model with postgres. User model is defined as below:

const Sql = require('sequelize');
const db = require("../startup/db");

const User = db.define('user', {
    id: {type: Sql.INTEGER,
         primaryKey:true,
         min: 1},
    name: {type: Sql.STRING,
           allowNull: false,
           min: 2,
           max: 50
        },
    email: {type: Sql.STRING,
            isEmail: true},       
    encrypted_password: {type: Sql.STRING,
                         min: 8},
    createdAt: Sql.DATE,
    updatedAt: Sql.DATE
});

I am looking for something like this in model User:

User.instanceMethods.create(someMethod => function() {
   //method code here
   });

The instance method can be access like this:

let user = new User();
user.someMethod();

There is Instance for model in Sequelize but it was not for the instance method. What is the right way to add instance method in Sequelize model?

2 Answers
const User = db.define('user', {
    id: {type: Sql.INTEGER,
         primaryKey:true,
         min: 1},
    name: {type: Sql.STRING,
           allowNull: false,
           min: 2,
           max: 50
        },
    email: {type: Sql.STRING,
            isEmail: true},       
    encrypted_password: {type: Sql.STRING, min: 8},
    createdAt: Sql.DATE,
    updatedAt: Sql.DATE
});


// This is an hook function
User.beforeSave((user, options) => {
   // Do something
});

// This is a class method
User.classMethod = function (params) {
    // Do something with params
}

// This is an instance method
User.prototype.instanceMethod = function (params) {
    // Do something with params
}
Related