Getting my Mongo on

This is the sixth post in a small series on Node.js. In this post, I will take a look at how to use my MongoDB from a Node app.

First, let’s install a driver for MongoDB: node-mongodb-native:

NPM really make it easy to get going!

Now, in order to connect to MongoDB, do this:

This should be done only once when the application starts up.

Then, to access a collection, do this:

Inside the function above, coll gives you access to do all the usual stuff to a MongoDB collection. To name a few, there’s insert, find, findOne, ensureIndex, count, etc.

As the node-mongodb-native documentation is pretty sparse, I’ve found it useful to open up a Node.js shell and connect with the driver, allowing me to inspect the various objects’ properties and methods, e.g. by inspecting db.__proto__ like so:

and coll.__proto__ like so:

Of course this way of barfing functions all over the place is not pretty, but it makes it possible to get a glimpse of what kinds of operations that can be performed on the various objects.

Getting Express to show flash messages

Now, this one might be obvious if you’re experienced with Node.js and Express, but it took me a while to figure out… therefore, so I know where to look the next time I forget it, and as a service to people Googleing in frustration; without further ado:

How to make Express render flash messages

First: Realize that flash messages are messages that are stored on the server for the duration between two requests from the same client, and thus are only available in the next request :D. Don’t try to req.flash(...) stuff and expect it to be available when render ing the view immediately after… (yeah, I did that for some time – pretty stupid, I know)… the locals object is how you do that.

Next: You need to make sure that the cookie decoder and session middleware are active:

Then: To store messages to be shown in the next request:

Note how nifty the PRG pattern can be implemented with Express. Note also that flash supports formatters, where the default supports %s and _, e.g.

resulting in something like this (with jQuery UI for formatting):

Last: When handling the next request, the flash messages are available in an object that can be retrieved only once by calling flash with no arguments on the request:

Now, having passed the flash object to my view, I can do this in my HAML view:

where the preliminary :if typeof flash != 'undefined' ensures that we don’t get errors if we haven’t transferred the flash object to the locals object.

The only annoying thing is that we need to remember to transfer the flash object in each request handler. I set out to write a piece of Node.js middleware that handled this, and I thought it was going pretty well until I realized that the middleware was executed in the wrong place. I haven’t found out if there’s an appropriate hook that can do this, so if anyone knows, please tell me :).

How Windsor’s decorators can save your life (almost)

Have you ever needed some kind of “master switch” in your application – i.e. some central place to flick a bool, resulting is changed behavior in numerous places?

Recently, we got the requirement that our application could function in two modes: active and passive. In active mode, the application must work like usual, whereas in passive mode, the app must not do anything to the outside world.

In our app, doing stuff to the outside world can be two things:

  • Writing stuff to a bunch of external SCADA systems.
  • Publishing status messages via NServiceBus.

which means that in order to implement passive mode, we need to avoid doing these two things.

Now, since everything in our app is wired by Windsor, and Windsor supports the nifty decorator pattern, implementing this “master switch” was a breeze!

The master switch

First, we implemented something like this to capture the switch itself:

which is registered like this:

Note th at the switch is a singleton, thus allowing all other services to have the same instance injected. Note also that concurrency is not an issue in our system – if MasterSwitch was to be used e.g. in an ASP.NET MVC application, it would have had a couple of locks in there or something similar.

Intercepting writes to external systems

All external hardware communication goes through an implementation of this interface:

so in order to abort all writes when we’re in passive mode, we added a new implementation of IExternalStuff that looks something like this:

Note how ExternalStuffWithMasterSwitch depends on IExternalStuff – this is where Windsor gets really cool, because if I remember to register my components in the following order:

then Windsor is smart enough to resolve the ExternalStuffWithMasterSwitch supplying the next available implementation of IExternalStuff, instead of entering a cycle.

Thus, we have cancelled all writes through IExternalStuff in our entire application with a few lines of extra code.

Avoiding publishing status messages

First, we needed som way to tell if a message was a status message, which was pretty easy – now all our status messages “implement” this marker interface which in turn implements IMessage from NServiceBus:

So, in order to “swallow” all published status messages when we’re in passive mode, we implemented this decorator to IBus:

which must be registered before NServiceBus’ own IBus gets registered:

I think this is a really cool example on how wiring everything with an IoC container provides some cool hooks in an application, allowing you to modify behavior in an extremely agile and non-intrusive manner.

2010 retrospective and 2011 resolutions

Now that ++year == 2011, and the last remaining effects of New Year’s Mojitos has finally left my brain, I think it is in order to take a look back at 2010 and evaluate a bit, and then maybe come up with some goals for 2011.

2010 retrospective

2010 has been pretty busy for me – check out this list of professional as well as personal activities:

  • My 2nd child was born in February :).
  • Wrote 34 blog posts spread pretty evenly over the year (except February).
  • Gave two talks on MongoDB in June, two talks on Castle Windsor in November and December, and two talks on NServiceBus in December.
  • Gave two 2-day introductory courses on getting up to speed with C#, .NET, dependecy injection, unit testing, and continous integration.
  • Gave one 1-day course as an introduction to C#, . NET, and WCF.
  • Gave 2 courses on NServiceBus.
  • Spent September and October on paternity leave.
  • Spent most of my other professional time as a development and architecture consultant on the core team of Dong Energy’s smart grid project, PowerHub. We’re controlling a hydro power plant right now at this very moment :).
  • Participated in two episodes of ANUGCast about MongoDB: Part 1 and part 2.
  • Learned a lot about new and emerging .NET technologies, NoSQL databases, and about architecture in general.

Looking back at all this, I think 2010 has been a little bit too busy – especially since most of the presentations and teaching happened in November and December :).

2011 resolutions

This is what I’d like to do in 2011:

  • I would like to continue doing all these great things in 2011, because that’s what makes my job alternating and fun, but ideally I would like to spread the activities some more.
  • I would like to start a pet project – i.e. build “something real”.
  • I would like to continue widening my horizon by cheching out non-.NET-stuff, like e.g. MongoDB and Node.js, which I am actually starting to like quite a bit.
  • I would like to continue contributing to OSS – either in a direct manner with code, or indirectly by blogging, tweeting, helping, creating courses, etc.
  • I would like to continue communicating with great people and be inspired.

Actually I should have hightlighted that last bullet – I guess it pretty much sums up my main goal for 2011 :).