Prelude : I'm not bashing the Express.js framework here. It was developed by people WAY beyond my skillset. I'm just saying it wasn't for me for various reasons.

I've been working on a very simple REST API for Kids In Touch. I'm trying to do this with Node.js. As I've been trying to learn Node.js, I've seen a million example API's using Express.js. So, I was plugging away using Express. To be honest, I didn't really like it. Trying to figure out how it all works is way beyond my skillset. So, I had just decided to roll my own API server using raw Node.js. Yes, it would be tough and simple and would likely lead to spaghetti code. Oh well.

However, yesterday, I discovered Hapi.js, and I was happy. Again, Hapi.js is way beyond my skillset. However, I found it easier to understand and use. So, I decided to try it out.

My first hurdle was connecting to MongoDB. I couldn't find a single example in any Spumko (FYI : Spumko is Walmart Labs repositories. I finally found this MongoDB plugin ( hapi-mongodb for Hapi by Nicolas Morel.

Being completely new to Hapi, I couldn't figure out how to even USE this hapi-mongodb plugin. Again, I didn't find an example on the Hapi.js documentation page for how to USE a plugin. Finally, I got smart and looked at the test for hapi-mongo and saw the integration.

Now, I've got a working example of using Hapi.js with MongoDB.

NOTE : This example uses a fork & pull request of hapi-mongo I made that exposes the ObjectID method. It is not absolutely required as it can also be accessed using : var ObjectID = this.server.plugins['hapi-mongodb'].mongodb;

var Hapi = require("hapi");

var dbOpts = {
	"url"		: "mongodb://localhost:27017/test",
	"options"	: {
		"db"	: {
	    	"native_parser": false
	    }
	}
};

var server = new Hapi.Server(8080);

server.pack.require('hapi-mongodb', dbOpts, function (err) {

    if (err) {
        console.error(err);
        throw err;
    }

});

server.route( {
	"method"	: "GET",
	"path"		: "/users/{id}",
	"handler"	: usersHandler
});

function usersHandler ( request ) {


	var db = this.server.plugins['hapi-mongodb'].db;
	var ObjectID = this.server.plugins['hapi-mongodb'].objectId;

	db.collection('users').findOne({  "_id" : new ObjectID( request.params.id) }, function(err, result) {

		if (err) return request.reply(Hapi.error.internal('Internal MongoDB error', err));

		request.reply(result);

	});

};

server.start( function() {
	console.log("Server started at " + server.info.uri);
});

Hopefully, this helps someone out.

Many thanks for Nicolas Morel for the plugin.