Mike Jenkins
Mike Jenkins

Reputation: 338

How to add instance and class level methods to a Model when using sequelize.define

I am working with Sequelize for the first time and am have structured my application in a similar way as shown in the official Sequelize github.

Each model is setup in its own file (e.g.):

user.mode.js

    const { DataTypes } = require('sequelize');
    
    // We export a function that defines the model.
    // This function will automatically receive as parameter the Sequelize connection object.
    module.exports = (sequelize) => {
        sequelize.define('user', {
            // The following specification of the 'id' attribute could be omitted
            // since it is the default.
            id: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: DataTypes.INTEGER
            },
            username: {
                allowNull: false,
                type: DataTypes.STRING,
                unique: true,
                validate: {
                    // We require usernames to have length of at least 3, and
                    // only use letters, numbers and underscores.
                    is: /^\w{3,}$/
                }
            },
        });
    };

Each of the models is then pulled in to the application as so:

index.js

    const modelDefiners = [
        require('./models/user.model'),
        require('./models/instrument.model'),
        require('./models/orchestra.model'),
        // Add more models here...
        // require('./models/item'),
    ];
    
    // We define all models according to their files.
    for (const modelDefiner of modelDefiners) {
        modelDefiner(sequelize);
    }

I'd like to add specific functions to each of the models so that the functions are available elsewhere in my application, however I am not sure how best to do this. There is an example in the Sequelize documentation however that only shows hows to do it if extending the model class. I could try and refactor to match this, but wanted to see if there was a way to do it as per the example setup provided by Sequelize.

Upvotes: 0

Views: 1056

Answers (1)

Anatoly
Anatoly

Reputation: 22758

You can save a return value of sequelize.define into a local variable and use it to define some static methods and even return this registered model to use it to call all model methods including your own ones.
See my answer and the question itself here

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: { type: DataTypes.BIGINT, allowNull: false, autoIncrement: true, unique: true, primaryKey: true },
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    User.belongsTo(models.Role, { foreignKey: 'role_id' });
  };
  return User;
};

Upvotes: 1

Related Questions