MongoDB singleton connection in NodeJs

In this post, I want to share a piece of useful source code to make a singleton connection in NodeJs. By using this piece of code, you will have always one connection in your NodeJs application, so it will be more faster. Also, if you are using NodeJs frameworks like ExpressJs, it will be useful too.

connection.js:

var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
//the MongoDB connection
var connectionInstance;

module.exports = function(callback) {
  //if already we have a connection, don't connect to database again
  if (connectionInstance) {
    callback(connectionInstance);
    return;
  }

  var db = new Db('your-db', new Server("127.0.0.1", Connection.DEFAULT_PORT, { auto_reconnect: true }));
  db.open(function(error, databaseConnection) {
    if (error) throw new Error(error);
    connectionInstance = databaseConnection;
    callback(databaseConnection);
  });
};

And simply you can use it anywhere like this:

var mongoDbConnection = require('./lib/connection.js');

exports.index = function(req, res, next) {
  mongoDbConnection(function(databaseConnection) {
    databaseConnection.collection('collectionName', function(error, collection) {
      collection.find().toArray(function(error, results) {
        //blah blah
      });
    });
  });
};

Now, you will have only one connection in your NodeJs application.

Download codes from Gist:

Let me know what you think :)

 
101
Kudos
 
101
Kudos

Read this next

Async vs. Sync I/O benchmark in NodeJs

As you know, NodeJs is a non-blocking I/O platform which gives you ability to do non-blocking and event-based functionalities. It has async methods for I/O but it also provide sync version of that methods as well. It means you can write... Continue →