Reputation: 9522
I'm just being curious. What is the proper way to open a database connection in nodejs with requires and dependency injection?
In php I would have created a connection once as a singleton in an global variable. However this seems not to be best practice in node. Thus I had the following questions:
I do know there are similar questions however the not fully seem to answer my question:
So my basic idea is:
/* DbService.js */
var Sequelize = require('sequelize');
module.export = new Sequelize('database', 'username')
same with models / instances
/* Foo.js */
var db = require("DbService.js");
export var Foo = db.define('foo', {...});
And in the code I than load the db / model by
/* server.js */
import Foo from './Foo';
Foo.findById('123').then(function(foo) {
...
};
var db = require("DbService.js");
db.query("SELECT * FROM `test`");
However in my mind this allways opens a seperate db connection and this feels wrong. So how would you do this probably?
Upvotes: 3
Views: 1795
Reputation: 9330
new Sequelize
instance, rather you create connection pool. If you don't specify configs for pooling sequelize will create with max 1 connection by default.new Sequelize()
) you're just initializing the connection pool. The actual connection will be created and kept in pool when an actual needs comes up like performing a query. Sequelize
instance, because of the nature of nodejs's module caching you'll always end up in same instance therefore same connection pool. NOTE - ES6 Modules not implemented yet in nodejs.
Upvotes: 1