0

I want to create a sequelize DB connection in my index.js file and then "pass" it to whichever model is being CRUDed. Is this possible in NodeJS and how?

index.js

const { Sequelize, DataTypes, QueryTypes, Model } = require('@sequelize/core');
const sequelize= require('./config/db');  //Here the DB connection is being exported

Then the router is called which calls the Controller which then requires the Model class below...

modelName.js

 class ModelName extends Model {}
 ModelName.init {
   fields.....
   sequelize   //This was initialized in 'index.js' and not in this file!
 }

When I try this out, I get 'Model is not defined' and 'sequelize is not defined' errors.....I am completely new to nodeJS :)

Nikster2014
  • 380
  • 3
  • 16

1 Answers1

0

You need to define model registration functions in model modules and then use them in index.js to register all models with already created Sequelize instance.
See my other answer here to learn how to do it

Anatoly
  • 20,799
  • 3
  • 28
  • 42
  • I read your answer and correct me if I'm wrong: You are reading ALL the models from a file and initializing them in the database.js file....is that right? – Nikster2014 Oct 22 '22 at 16:26
  • Yes, exactly. Strictly speaking you can skip storing them in a module itself because you can get them from `models` prop of the Sequelize instance but I'd still prefer doing this way – Anatoly Oct 22 '22 at 17:50
  • So by doing so, is your script not consuming a lot of memory by allocating it to model variables that may or may not be used in the incoming call? – Nikster2014 Oct 23 '22 at 05:44
  • All models and their associations should be registered proir to using them in any controller. Are you sure you want to make sure every time what models depend on each other to initialize them on demand in a certain controller. Nobody usually does so.Just register all of them at once and that's all. It not THAT huge amount of memory you should be concerned. – Anatoly Oct 23 '22 at 13:16