How to configure a mongodb connection in expressjs for production

In this short tutorial, I will describe how to create a mongodb connection so that the connection can be reused throughout the whole express app. The main benefit of this is to not open multiple connections and to leak the memory.

From the official mongodb docs, creating a simple connection to mongodb uses the following code:

MongoClient.connect(url, function(err, db) {  
  assert.equal(null, err);
  console.log("Connected successfully to server");
  // do something with db 
  // ....
  db.close();
});

But with the above we can't reuse the db variable outside the code. One possible way to reuse the db variable is to make it global or used module.exports. But as we know global variables must be avoided in javascript as much as possible. So to reuse the db we just inject into req parameter and also set in expressjs using app.set.
Here's the full code:

// file dbconnection.js
module.exports = function(app, uri, opts) {  
    if (typeof uri !== 'string') {
        throw new TypeError('Error: Unexpected mongodb connection url');
    }

    opts = opts || {};
    var property = opts.property || 'db';

    var connection;
    return function expressMongoDb(req, res, next) {
        if (!connection) {
            connection = MongoClient.connect(uri, opts);
        }

        connection
            .then(function (db) {
                req[property] = db;
                app.set('mongodb', db);
                next();
            })
            .catch(function (err) {
                connection = undefined;
                next(err);
            });
    };
};

The above code only create connection if no mongodb connection is made. It also inject db variable of mongodb into req object and set it locally to mongodb so that it can be reused in express api's and in any function.

Now to use the connection, you have to first initialize it:

var connection = require('./dbconnection');  
// url and optional config.
app.use(connection(app, 'mongourl', {});  

And here's the usage in api's:

router.get('/', function(req, res) {  
  var db = req.db;
  // do anything
});

// elsewhere, in other files 
function myFunc() {  
 var db = app.get('monogdb');
}