0

I new to express. Now i am working in mongodb connection and CRUD activity. I created a connection in connection.js. And i get the database instance in app.js. The same DB instance i need to share register, login and some other modules without calling connection.js in these modules again. Or i need the proper answer to resuse connection in multiple modules in express.

Thanks in Advance,

user3446501
  • 31
  • 1
  • 6

1 Answers1

0

You can setup a db module like so:

// db.js

let _db;

module.exports = {
    getDb,
    initDb
};

function initDb(callback) {
    //connect to db and set _db to the new connection.
}

function getDb() {
    assert.ok(_db, "Db has not been initialized. Please called init first.");
    return _db;
}

Then somewhere in your app initialization you can do:

//app.js

const dbmodule = require("./db.js");
initDb(function(err){
    // more app init;
});

then in your other modules, say login.js, do:

//login.js

const dmModule = require("./db")
const db = dbModule.getDb() //at this point the db should have been initialized.
Sello Mkantjwa
  • 1,798
  • 1
  • 20
  • 36