Blog Rolling with MongoDB, Node.js and Coffeescript

This morning I woke up with a lingering thought on my mind that was left over from recent conversations. In the technical community we often get so invested in our work that rather than talk about the simple building blocks that build our success we talk about the huge breakthroughs we make. The problem however is that our breakthroughs most often aren’t accessible to someone who wants to just get started. So today I will give an intro tutorial to using node.js, coffeescript and mongodb to build a simple blog. It builds off the concept in a tutorial I first used to learn node.js more than a year ago, but with a completely from scratch approach. In this tutorial I will also cover practicing Behavior Driven Development using Mocha.

Getting Started

Quite obviously, you’re going to need node.js and mongodb installed. I recommend downloading and installing from the node.js website and following the instructions. I will note that this tutorial covers 0.6.7 so if you come across this post a year from now the API might have changed significantly since then. You will also need mongodb installed, you can download it here. If you use Ubuntu (or some other Debian derivative) you should consider installing from their apt repository. OSX? No problem, you can also install it via homebrew or macports.

Finally, since we’ll be using coffeescript for this tutorial, run npm -g install coffee-script (you might need to sudo) to install coffeescript. Run coffee from the commandline to access the coffeescript REPL. If all works well, install these additional packages listed below via npm that we’ll be using throughout the tutorial.

  • express
  • mocha

Now let’s bootstrap our project structure. Type express coffeepress to generate a skeleton express project structure. You should see output similar to the following:

Notice how at the end it says to cd to the directory and type npm install? Let’s follow those instructions. Let’s run what we have so far by typing node app.js and navigating to http://localhost:3000. This is the default structure that gives a good starting point. Feel free to investigate the files under the directory before moving on. I even suggest poking around by changing the view a bit and changing the title from express to “My Coffeepress Blog”.

Porting to Coffeescript

At this point, let’s port our backend to coffeescript. I used to copy and paste files into the js2coffee website but you can also install js2coffee via npm. So run the following:

Now you can run coffee to run the same app, but now in coffeescript. Take a look at the resulting files to get a feel for what has changed. New to coffeescript? Then I recommend taking a gander at before moving on. Here is the project structure so far.

Basic Navigation

I like to try and work my way from the outside in while developing a site or feature, materializing components into existence as I need them. So let’s start by working on the initial navigation of the site with some simple in-memory storage of blog posts. This is a good time to get our test framework setup and write a few simple tests against our routes. Normally I prefer to not write tests against my routes, shoving logic into heavy models or services. However I have come to learn that untested components of a system serve as a gravity well for untested code that eventually leads to clients calling you about broken applications. What follows serves as both an introduction to Mocha as well as express’ routing mechanism.

Let’s edit our package.json to include our test framework dependencies.

We include should so that we can use BDD style assertions (more on this in a bit). Write a simple test case located at test/ with the following code to get us started with mocha

Now run this by typing mocha from the root of the project directory. It should pass. Let’s go ahead and make it fail by changing 4 to 5 and rerunning it. Hopefully this gives you a good feel for our test framework before we move on and change this test to reflect our existing index route. Swap the code in this test out with the following.

Here we fake our requests and response in order to capture what is passed into the response. We fake the render method and verify that our rendered view is “index” and that the variable title is equal to what we expect to be passed in. Run the tests and make changes to your route to make it pass.

Now let’s add a post variable that will be an array of posts we’ll display on the front page. Add the following assertion right after the title assertion:

Run the tests to see it fail and change the route to have a posts array variable available in the template.

Unfortunately you’ll notice that the test fails. This is due to a subtle difference between equal and eql. The former enforces strict equality while the latter is a bit looser, so we change our assertion to use eql. Take a look at the should documentation for more information.

Next let’s write tests for the “new post” route.

Run it, see the failure, and rework our file to include the route (with no implementation yet)

You’ll notice our test passes. That’s not good. Why? Because we put our assertion in our req.render callback, which never gets executed. Doh! How can we make absolutely sure it gets called during our test run? Old school thinking would have you assign a local variable outside the scope of the callback that gets assigned during execution and then can be verified against later on. However we have no guarantee that the routing logic will be synchronous!

Thankfully mocha has a feature that allows for easy testing in these situations. In the method declaration of our test specify a parameter named done. This is a callback that we can call anywhere to indicate the test is done. Basically the test will wait up to a default of 2000ms for it to be called. With this in mind, let’s modify our tests with the following:

If we run this via mocha now we’ll notice that we have one failure. Let’s go ahead and implement the route and connect it into our router.

And connecting it up in the

Modifying the Views

This code is useless without views, so let’s modify our views a bit. Let’s modify our layout.jade to link to the new posts page. This layout also makes use of twitter bootstrap because I’m too lazy to design something for this tutorial. :)

And create our add_post view at views/add_post.jade. An interesting thing to note here that I’ll touch on in a bit is that I prefix the input names with post.

Now let’s add another route to handle the post. This time I’m going to kind of skip delving into the details of writing the test, but you can look at what I have so far here if you’d like to see it.

For now, we’re just going to store each post in an array. Nothing fancy yet. We also add a new route to We could refactor or use some express-mvc plugin to reduce adding each route by hand, but I think it’s good to do it like this to get a feel for express’ low level routing mechanisms.

Finally, we’ll add one last view for viewing a single post:

Go ahead and start the application up and navigate to http://localhost:3000. Post a few posts and play around a bit. You can see the finished application we have so far here.


Whew. I hope I haven’t lost you yet. Especially with the tests against the routes… I know those are always a bit painful! Now that we have functional blog let’s make it work by storing posts in mongodb using Mongoose.

Let’s add a dependency on mongoose to our project and freeze it at version 2.4.10. As always, run npm install to bring it in. Now we’ll create an initial test to just test mongoose out.

Here we import both mongoose and the model object that we’re going to create. Since we want our test to start with a clean slate, we use the before hook (which runs once before anything else in the test runs) to both connect to the database and then remove all of the Post objects from mongodb. We pass the done callback to the remove call so that tests don’t run until all Posts have been removed.

Now we create a new Post instance. You can pass an object literal in to set properties on the model, so we do that here. Finally, in our callback we look the post back up and verify certain attributes have been set. It’s a dumb test (and in fact I rarely test mongoose’s behavior like this), but it does verify that we’ve configured our model correctly.

Now let’s implement our model to make the test pass.

Pretty simple. Now let’s refit our routes to use the Post model instead of an in memory array.

That’s all good and dandy, but one last hiccup is our tests for our routes now fail. Chalk this one up to not having any abstraction or dependency injection in place, but that is fine for now, we’ll live with it and change the tests.

Finally we need our app to actually connect to mongoose when we run it. I like to do this based on the express configuration. This is immensely important if you have mongodb running on servers separated from your application. For this example we’ll just use the databases coffeepress-dev and coffeepress-prod.

Run it and write a few posts. Restart the app and you’ll see the posts still there. Woot!


Well, that about wraps it up… you can see this tutorial in it’s finished glory on the finished branch of the repository. There’s a bit missing out here that we’d implement in the real world. Obviously some kind of authentication would be in order if we took this further, possibly using mongoose-auth. We’d also want to add some validation when posting. These are all excellent topics for future posts but for now I hope this was enough to help you get going! :)

  • Tarun

    I just started rolling with nodejs, coffeescript, and mongoDB.
    And your post is a God-send for me,

    Thank you for all your effort.

  • Kamal Reddy

    Cant thank you enough for your efforts.
    Loving node

  • Seth

    Thanks for the excellent tutorial!
    I’m receiving the following error after reaching the end of the tutorial:

    1) Post “before all” hook:
    Error: timeout of 2000ms exceeded
    at Object. (/usr/local/lib/node_modules/mocha/lib/runnable.js:126:14)
    at Timer.ontimeout (timers.js:94:19)

    Any ideas?

  • James Carr

    @Seth I’ve seen this happen when it failed to connect to mongoDB. Is MongoDB running?

  • sami

    Hi, I followed the tutorial. Cannot run the first test. I tried mocha test/ –compilers coffee:coffee-script but it returns AssertionError: expected {} to equal 4. All the modules seem to be installed in node_modules folder. Is this syntax error or sth else? Any ideas?

  • Ryan

    Thanks for this great tutorial. I am trying to follow it, but it seems like it is already out of date. I have been successful up to the point where you start using Mocha. Apparently in the newer versions of Mocha it does not support coffeescript by default.

    Also you use the module ‘should’, but you never mention installing it. I am getting an error Error: Cannot find module ‘should’. I tried installing it with npm install -g should, but that does not help.

    So I tried skipping the mocha stuff, but you start talking about a file, but we never created one, is this created by mocha? I have an file in the routes folder, is this the same file?

    • James Carr

      Sorry, but the tutorial does indeed seem to already be out of date. I will get around to updating it as soon as I can tonight.

      As for, that should be I’ll review the post and see if I skipped its creation. If I have I’ll add it back in

      • Ryan

        Thanks for catching my typo. I have also been checking your git hub repository, it also does not have a file.

        Also your link to the finished project is pointing to the wrong tree in Git hub.

        Thanks again

  • Jameson Quinn

    Nowadays, you don’t just type “mocha”, you have to type “mocha –compilers coffee:coffee-script” to get it to work with coffeescript tests.

  • Giles

    Hey James,

    Great tutorial, just wondering if your thinking of updating it anytime soon?

    It comes up as number 1 on Google for ‘create a blog in node’ so would be great if it was up to date.



  • Matt Heath

    great tutorial! thanks for taking the time, will you update at any point?

  • Novi

    Hi James,

    I tried your tutorial but I’ve got an error when I converted app.js to :

    var compiledWrapper = runInThisContext(wrapper, filename, true);
    SyntaxError: Unexpected string
    at Module._compile (module.js:434:25)
    at Object..js (module.js:464:10)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Array.0 (module.js:484:10)
    at EventEmitter._tickCallback (node.js:190:38)
    Do you have any idea? Thanks a lot.

  • neil

    @sami is getting a version mismatch. It is answered here:

    However, ‘npm update’ wasn’t fixing it for me. I had to use ‘npm install’

  • opensas

    Excellent article!

    I’m currently using jasmine-node, and I was wondering why you decided to go with mocha… any adavantage you can recall?

  • pixelBender67

    can you update this tutorial ? Trying to write my own blog with node and express :)