I'm trying to build out a basic database schema using Express and Sequelize. I define all of the models in separate files. I have a single file (models/index.js
) where I create an instance of the Sequelize class, import the models, and establish the relationships among the models. I also have multiple controllers that each need to have access to the models exported from models/index.js
.
Here's the file where the models are imported:
// models/index.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize('myApp', 'username', 'password');
var User = sequelize.import('./users');
var Contact = sequelize.import('./contacts');
var Conversation = sequelize.import('./conversations');
var Medium = sequelize.import('./mediums');
User.hasMany(Contact);
Contact.belongsTo(User);
Contact.hasMany(Conversation);
Conversation.belongsTo(Contact);
Medium.hasMany(Conversation);
Conversation.belongsTo(Medium);
module.exports.Sequelize = Sequelize;
module.exports.sequelize = sequelize;
module.exports.User = User;
module.exports.Contact = Contact;
module.exports.Conversation = Conversation;
module.exports.Medium = Medium;
Here's one of the controllers that needs access to the models.
// controllers/users.js
var models = require('../models');
module.exports.addUser = function () {
};
module.exports.getUser = function () {
};
Here's another controller that needs access to the models.
// controllers/contacts.js
var models = require('../models');
module.exports.addContact = function () {
};
module.exports.getContact = function () {
};
module.exports.getAllContacts = function () {
};
My concern relates to the fact that both controllers require the models/index.js
file. Each time the models/index.js
file is required, a new instance of the Sequelize class is created, which establishes a new connection to the database. Does anybody have any suggestions to avoid multiple instances of the Sequelize class?
Thanks in advance!