Simple MongoDB node.js client module

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:

    var client = require('mongodb').MongoClient,

    module.exports =  {
        connect: function(dburl, callback) {
                function(err, db){
                    mongodb = db;
                    if(callback) { callback(); }
        db: function() {
            return mongodb;
        close: function() {

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):

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.');

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:

var mongodb = require('./mongo_client');

    .find({someField: 'myquery'}, {}, options)
    .toArray(function(err, coll) {
        if (err) { throw err; }

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!

4 thoughts on “Simple MongoDB node.js client module

  1. Hi when i tried your mongodb client but when I try to use the connection created by server.js I get an error:

    TypeError: Cannot read property ‘collection’ of undefined.

    Can you please tell me if i am doing anything wrong?


  2. Hi, it looks like the connect() statement isnt working correct, as once it actually connects it populates db() so that when its called later, collection can be chained. Collection is failing to chain because db() is undefined (according to your error).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s