I have implemented a server application using mongodb for logging. I implemented data access using some classes of providers, as shown in the example.
provider.filelog.js
var Db= require('mongodb/db').Db, ObjectID= require('mongodb/bson/bson').ObjectID, Server= require('mongodb/connection').Server, log = require('lib/common').log; FilelogProvider = function (host, port, database) { this.db= new Db(database, new Server(host, port, {auto_reconnect: true}, {})); this.db.open(function(){}); }; FilelogProvider.prototype.getCollection= function(callback) { this.db.collection('filelogs', function(error, log_collection) { if (error) callback(error); else { log_collection.ensureIndex([[ 'created', 1 ]], false, function(err, indexName) { if (error) callback(error); callback(null, log_collection); }); } }); }; FilelogProvider.prototype.findAll = function(callback) { this.getCollection(function(error, log_collection) { if (error) callback(error); else { log_collection.find(function(error, cursor) { if (error) callback(error); else { cursor.toArray(function(error, results) { if (error) callback(error); else callback(null, results); }); } }); } }); };
Since I use Grasshopper as my http middleware, I can easily deploy providers using the DI functionality provided by gh:
server.js
gh.addToContext({ providers: { filelog: new FilelogProvider(conf.mongodb_host, conf.mongodb_port, conf.mongodb_database), status: new ServerstatusProvider(conf.mongodb_host, conf.mongodb_port, conf.mongodb_database) }, log: log });
Access to suppliers in each controller function is now great:
gh.get('/serve', function() { this.providers.filelog.findAll(function(err, res) {
This implementation is pretty specific to Grasshopper (since it uses DI), but I think you get this idea. I also implemented the solution using express and mongoose, you will find here here . This solution is a little cleaner than using the native driver, as it provides models for use with the database.
Update
Just for the sake of it: if you really want to adhere to the DRY principle, stop doing ORM implementation and use Mongoose . If you need special features like Map / Reduce, you can still use your own driver (which Mongoose is built on).