Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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) {
var db = new Db('your-db', new Server("", Connection.DEFAULT_PORT, { auto_reconnect: true }));, databaseConnection) {
if (error) throw new Error(error);
connectionInstance = databaseConnection;

This comment has been minimized.

Copy link

commented Apr 5, 2013

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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.