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,

0

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.