5

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 2

10
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
}
Sign up to request clarification or add additional context in comments.

1 Comment

This should be selected as the real answer of the question. And not the link posted by the owner of the question.
-1

Here is the answer for the question. See reply by Mariano.

Cannot access Sequelize instance methods

Here is more reading: https://codewithhugo.com/using-es6-classes-for-sequelize-4-models/

1 Comment

So the user user938363 posts a question. And then he adds a simple link as an "answer". And then he decides that his link is the proper answer, despite the fact that another user (Ugo Giordano) posted an actual answer with useful working code below. Uhmm, interesting!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.