I'm using MongoDB in Node.js by encapsulating it in a module:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(..., function(err, db) {
if (err) {/* handle */}
exports.db = db;
});
Now wherever I want to use mongoDB connection I just
var mongo = require('mongo');
mongo.db.collections(...)
The problem is that for some time the connection isn't initialised and I get the 'undefined db' problem.
I know that I can register a callback for connection opened, but I don't want to couple that with script execution.
Is there a better practice for awaiting for connection to be started (for all of the places?).
I would refer to this implementation as the example of complete encapsulation: strongloop/loopback-connector-mongodb. The difference is that instead of exporting internals (access to mongo database instance), you expose the object (your encapsulating module) and its methods.
If you don't want to implement it yourself but instead what to make use of a ready solution you can try something like mongoskin, which is a promise wrapper for node-mongodb-native driver.