Node js single mongodb connection
If you make your custom callback node style (i.e. function(err, result)), you can simplify this greatly:

'use strict';
var MongoClient = require('mongodb').MongoClient,
    db;


module.exports = function connectToMongo(url, callback) {
    if (db) { callback(null, db); }
    else { 
        MongoClient.connect(url, function(err, conn) {
            db = conn;
            callback(err, conn);
        });
    }
}


And use it:

var connectToMongo = require('./mongodb.js');

/* ... */

connectToMongo('mongodb://127.0.0.1:27017/test', function(err, db) {
    collection = db.collection('test');
});




An even better option would be to use Promises. I use bluebird in my projects, but we'll soon have native Promise support (bluebird will probably still be better).

var mongo = require('mongodb'),
    Promise = require('bluebird');

Promise.promisifyAll(mongo);
Promise.promisifyAll(require('mongodb/lib/mongodb/db').Db.prototype);

var db;

module.exports = function connectToMongo(url) {
    if (!db) {
        db = mongo.connectAsync(url); //This returns a promise!
    }
    return db;
};


Then use it like

var connecttoMongo = requiure('./mongodb.js');
connectToMongo('mongodb://127.0.0.1:27017/test').then(function(conn) {
    //Do stuff here
});