Skip to content

Instantly share code, notes, and snippets.

@afshinm
Created April 5, 2013 10:57
Show Gist options
  • Save afshinm/5318436 to your computer and use it in GitHub Desktop.
Save afshinm/5318436 to your computer and use it in GitHub Desktop.
MongoDb singleton connection in NodeJs
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);
});
};
@jfromaniello
Copy link

I use something like this, but with two main differences:

  • if you call twice this function before the callback is executed you will create two connections. I usually define Db and server outside the function and i check db.openCalled.
  • also, most of the time you need to authenticate after the open with db.authenticate

Another good tip will be to keep all the connection settings in one environment variable as mongodb://user:password@host:port/database

So, I do something like this:

var url        = require('url'),
    parsedUrl  = url.parse(process.env.CONNECTION_STRING || 'mongodb://localhost/something');

var connectionInfo = {
  host:     parsedUrl.hostname,
  port:     parseInt(parsedUrl.port, 10),
  name:     parsedUrl.pathname.substr(1),
  user:     parsedUrl.auth ? parsedUrl.auth.split(':')[0] : null,
  password: parsedUrl.auth ? parsedUrl.auth.split(':')[1] : null
};

@afshinm
Copy link
Author

afshinm commented Apr 5, 2013

Nice one @jfromaniello.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment