Wednesday, January 16, 2013

CRUD with Mongo Helper

MongoDB is an excellent database solution that has it's quirks.  Node is a great server-side solution.  I'm using both in my latest project to revolutionize online education.  Unfortunately, the combination of the two can be verbose and prone to errors.  There are other solutions but those can be unnecessarily complex in their own way.

Let's say we wanted to add a new record to an existing collection.  Using the native mongodb driver, we'd need the following:

var mongo = require('mongodb')
  , server = new mongo.Server('localhost', mongo.Connection.DEFAULT_PORT, {auto_reconnect: true})
  , mdb = new mongo.Db('blog', server, {safe: true});

module.exports  = {
  insert = function(insertQuery) {
    mdb.open(function(err, db) {
      db.collection('recoding', function(err, collection) {
        collection.insert(insertQuery, function(err) {
          if(err) { /* handle errors */ }
          db.close();
      });
    });
  }
}
and that's only for a simple insert, without a callback.  Instead, I wrote up a simple CRUD app to help out, which reduces the above to the following (which is simple enough that one wouldn't need a whole function):

var mongoHelper = new (require('mongo-helper'))();
module.exports = {
  insert = function(insertQuery) {
    mongoHelper.insert('recoding', insertQuery);
  }
}
The one thing that's become more complicated is the declaration of mongoHelper.  Using the native driver allows for a much more flexible application with regard to settings.  I tried to keep it simple, while still allowing for customization.  The new method allows the user to pass settings to Mongo Helper, while letting defaults remain default.  For instance, if we wanted to use a different database:
var mongoHelper = new (require('mongo-helper')({dbName: 'users'});
Mongo Helper only supports the four basic CRUD operations for now. I plan on adding support for things like findOne and database storage of settings soon.

You can find the code/docs for Mongo Helper at my Github.  If you liked this, follow me on Twitter for more updates.

No comments:

Post a Comment