Inspired by watching TJ Hollawaychuk's supremely awesome screencast about using route-specific middleware at http://expressjs.com/screencasts.html, 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 locals.next 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.
Monday, April 18, 2011
Thursday, April 14, 2011
Monday, April 11, 2011
THIS IS OUT OF DATE CHECK OUT THIS NEW ARTICLE INSTEAD
MongoHQFree 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.
DifficultiesOne 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 WrapperI 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 piecesTo get this custom driver up an running it's very simple.
- Initialize it.
- Register your collections.
- User it