Handle mongodb connection in expressJS

You've got several reasonable options. It's really a matter of personal preference.

Create another module that opens the connection and have all other modules use that module:

mongo_connection.js

In that file, you'll put the connection and authentication code. Export the db instance for example:

exports.db = db;

In other files, you could require it:

var connection = require('./mongo_connection.js');
var db = connection.db;

Or, I often create the connection once (in a module), and then pass that to an initialization function in routes:

var users = require('./routes/users.js');
users.initialize(db);

I often do that as there's other common configuration work and settings that I want to provide to the routes:

var initialize = function(app, config) {

};

If you pass the express app instance around, you could set it as well:

app.set('mongo', db);

And then use app.get('mongo') to fetch it.


You can use express-mongo-db middleware for this. It will create and cache connection to mongodb so you can use it inside findAll through req.db property.