0

Suppose inside a model you have the following Sequelize instance method:

const Admins = require("./admin");

Organization.prototype.getAdmins = function () {
    // option 1
    return Admins.findAll({ where: 
        { organization_id: this.getDataValue("id") }
    });

    // option 2
    return sequelize.Admins.findAll({ where: 
        { organization_id: this.getDataValue("id") }
    });
};

Sometimes I see it written as option 1 and sometimes as option 2. When do you need which option? That is, when do you need to prepend sequelize. before the model that you are referencing?

Nick
  • 3,496
  • 7
  • 42
  • 96

1 Answers1

0

It depends on what you import in a certain model file: sequelize instance or an initialized model (that also should be initialized using sequelize instance).
The goal is to access needed model to call its methods like findAll. It's up to you what approach to use but I'd recommend to access all models from sequelize instance or from your own object that will store all initialized models (see my answer here).

Anatoly
  • 20,799
  • 3
  • 28
  • 42
  • Thanks @Anatoly, At the top of the model file, I have: `const sequelize = require("../db");`. This calls on a file that includes `const { Sequelize } = require('sequelize');` `const sequelize = new Sequelize();`. Am I correct to conclude that with this setup I should use option 1? – Nick Jun 09 '22 at 17:36
  • It would be much better to return a function that register a model and pass `sequilize` to it. That way you avoid importing `sequelize` in model files. – Anatoly Jun 09 '22 at 19:55