Deep Dive Into Node.js and MongoDB - Day 5


In case you missed the other days:
Day 1 Deep Dive
Day 2 Deep Dive with MongoDB
Day 3 Deep Dive with MongoDB
Day 4 Deep Dive with MongoDB

Tonight's posting is less about performance comparisons, but with getting my deep dive into a more "real-world" project. In doing these deep dives I'm learning when Node.js is a better tool to utilize verses ASP.NET in REST service scenarios. Going along this line, I really wanted to start shifting from the "hello world throw all your code in one file" and start structuring it like I would a C# project breaking out routes from the main file and abstracting out the database functionality. So without further discussion let's dive in.


As mentioned previously, t this point I am going to assume MongoDB is up and running, if you do not, check my first day post for details on how to get it up and running.

Benchmarking Tool

Although I did not mention this in the intro, I made some extensive changes to the WPF Benchmarking tool to set it up to handle future testing more structured and dynamically than before. Benchmarks are now abstracted away and dynamically populating a dropdown, for those curious here is a screenshot:

Splitting out Routes

As mentioned in the intro, the main focus of tonight's deep dive is into start structuring of the app into a more real world app. The first step in my mind was to do away with the single server.js file I had been using this week especially with the MongoDB related code also mixed in there.

After some restructuring I now have two JavaScript files: server.js and routes.js.

My server.js is now just a few Express init calls:

var express = require('express');

var app = express();


Only thing left in my mind is to pull the hard coded port number (1338) into a config file or constants file.

My routes.js:

var express = require('express');
var mongojs = require('mongojs');

var dburl = 'localhost/day2innode';
var collections = ['posts'];

var db = mongojs(dburl, collections);

var postData = db.collection('posts');

var router = express.Router();

router.get('/api/Test', function (request, response) {
    var id =;
    var newData = { 'id': id, 'likes': 2 };

    postData.insert(newData, function (err, post) {
        if (err) {
            return response.json({ message: err });

        return response.json({ message: true });

module.exports = router;
For those keeping up with this deep dive, not too much new code here outside of defining the module.exports and express.Router. One thing I want to do in this file is to utilize mongoose to clean up the MongoDB calls and to pull the collection and database url from a configuration file similiar to the server port number in the server.js file.

Next up...

As mentioned above I am planning to start deep diving into mongoose to clean up some of the MongoDB database code I wrote the other night. Lastly, all of the code thus far is committed on GitHub.
none on this post