Here’s a simple MongoDB client module I use when prototyping projects in node.js.

This module allows me to connect and reuse a connection db object easily via a simple module. Many times I’ve found myself writing connection code repeatedly in modules or just generally not keeping my functions DRY when it came to working with MongoDB. In a recent project I was working on, I decided to throw together this quick module and I think it worked out nicely.

Nothing too crazy or fancy, but it gets the job done and makes my life easier. Heres the code:

[code lang=”javascript”]

(function(){

var client = require(‘mongodb’).MongoClient,

mongodb;

module.exports = {

connect: function(dburl, callback) {

client.connect(dburl,

function(err, db){

mongodb = db;

if(callback) { callback(); }

});

},

db: function() {

return mongodb;

},

close: function() {

mongodb.close();

}

};

})();

[/code]

Simply save that as mongo_client.js in your project somewhere. This module has 3 functions:

  • connect: open a connection to the MongoDB server and save that connection object as a local variable of the module
  • db: a function that simply returns the instance of the connection object (that was set via connect)
  • close: a function that closes the connection

  • Note: the db() function will return null if connect is not called first, since the mongodb local variable is never populated with a value.

** Note: also note that this module also requires the actual mongodb module, which will need to be installed via ‘npm install mongodb’.

To use the module, first configure a connection one-time somewhere in your app (maybe server.js):

[code lang=”javascript”]

var mongodb = require(‘./mongo_client’);

// wire up your express app or whatever then:

mongodb.connect(‘mongodb://localhost:27017/mydatabase’, function() {

console.log(‘Connected to MongoDB.’);

});

[/code]

Now that your MongoDB client is connected, a db reference is always available simply by requiring the mongo_client and calling its .db() function like so:

[code lang=”javascript”]

var mongodb = require(‘./mongo_client’);

mongodb.db()

.collection(‘mycollection’)

.find({someField: ‘myquery’}, {}, options)

.toArray(function(err, coll) {

if (err) { throw err; }

console.log(coll);

});

[/code]

Super basic, but works well for me! Hope you find this useful and if anything exposes some ideas on how you can reuse elements in your modules (using self-invoking functions) without requiring to do the same tasks repeatedly throughout your code. Enjoy!