Monday, April 18, 2011

Express Pagination Middleware Simplicity

Inspired by watching TJ Hollawaychuk's supremely awesome screencast about using route-specific middleware at, I threw together a simple use case for myself: pagination. While pagination might not be an obvious choice for middleware, it works here because it doesn't need to know anything about the route that's using it, though in this case it may take advantage of some passed in variables if they exist!

Here is a partial using EJS syntax that will display some previous / next arrows wherever you choose to place them. Notice I'm using locals.prev and here, which works, becuse I'm not sure those variables will even exist. In these cases you access them as properties off of the locals object in the view, which means you don't have to do this if (typeof prev !== "undefined" && prev), which is a little more verbose if you ask me:

I liked how easy the middleware approach was over having specific pagination logic in each route that used pagination. Express is fantastic for letting me send in multiple functions that I can chain together by calling next(). In this example, without using the middleware I would have had to wrap each paginated function in the count() database call, which would give me an un-neccessarily long callback chain. I prefer the simple middleware approach allowed by express.

Thursday, April 14, 2011

JS Codings Standards

Here are some JavaScript coding standards/conventions I've been thinking about lately. I put this together pretty quickly, so it may contain some errors. What you think about these? Are there other conventions you support? Please post your feedback and/or corrections and suggestions!

Monday, April 11, 2011

MongoHQ and Node



Free MongoDB hosting for playing around with Mongo. Free for 16mb of storage. $5/month for 256mb. It's good for small stuff and getting started with Mongo.


One of the problems I found while connecting to MongoHQ from node was the authentication. Most of the MongoDB libraries for node are very simple to use, but cut some of the features from the mongodb native library like authentication (or at least make it difficult to access), so I ended up rolling my own wrapper to make the authentication step as easy as possible.

Custom Wrapper

I wrote a simple wrapper to the Node MongoDB native driver that made it easier to hook into MongoHQ, which requires authentication. It may be useful to other people as well:

Connecting the pieces

To get this custom driver up an running it's very simple.
  • Initialize it.
  • Register your collections.
  • User it

Docs and Help

Locals in ExpressJS

Using Local Variables in Express

ExpressJS allows you to define "locals" which are variables available to the view in multiple places and in multiple ways. Here are a few examples.

Incrementing a Count Variable With Mongo

The main line that you need to look for is the following one:
db.logs.update({}, {$inc:{count:1}});