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:
- Where would you open a db connection in node?
- Would you open the db connection once or multiple times?
- How can I open the db connection only once while keeping es6 module imports?
- How can I open multiple db connections through es6 module loading?
- If I import the same database multiple times, does it result in multiple connections?
- I rather know and like to control how many connections are opend by my server. E.g. if I write a backend worker with low db access I rather only open one db connection there as running an express server I'd like to open a connection per request. How can I achieve this?
I do know there are similar questions however the not fully seem to answer my question:
- Singlton in Node ES6
- Where to connect to the database in node?
- NodeJS Express Dependency Injection and Database Connections
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?