Mike Valstar

Web Development, Programming, Random Thoughts

Twitter Status...

Coding with Node.js: Part 6; Displaying an Archive

Posted on
Code Updated The code below has been updated for express 3.0 here

Now that we are pulling our posts from the database the next step is to allow users to browse old posts. And just in time since this will be the 11th post to the blog.

The key items we need for people to be able to view an archive of the website is a previous and next button on the main page, and an archive listing of posts (in this case by month).

In addition to the above I'll be adding a new column to the blog posts allowing me to group posts.

The Group Column

To start off lets add a new column to the Blog post table. The nice thing about Mongo is that you can do this very quickly by simply adding the column to the schema like so:

Database.js

With the new column in place and saveable you can now go through your old posts and add a group where applicable.

AdminPages.js

I'll leave adding the new column to the admin pages as an exercise for the user, but you can see the finished result here.

The URLs

For the new archive functionality it's best if we add in some new URL masks to cover all the possibilities we'll want in the future: Paged number, year/month, group, search.

I've rolled these into a single handler to simplify the index page and to allow us to expand easier in the future:

Util.js

PublicPages.js

The Archive Sidebar

For the sidebar we need to preform a simple map reduce to find the groups of months that have posts. A MapReduce is similar to a GROUP BY statement in a SQL database, in an SQL db we would write "GROUP BY year(datecol), month(datecol)" but for mongo we will do the following:

PublicPages.js

This includes the search and month search as well.

Additional Ideas / The Future

Based on the code above it would be pretty easy to do any of the following: * Last page button * Add a search box somewhere on the site * Add a list of groups * Add a title-only list of articles (an all articles page)

The Code

All code created for this website is available on the github page page and this tutorial specifically is available here: https://github.com/mikevalstar/mikevalstarcom/tree/NodeTutorial_pt6

Next Time

Next time I'm going to talk about in-memory caching with node, in this case for the archive sub-menu. We'll go over a couple techniques and the reasons for choosing each.

bp_112
comments powered by Disqus
Mike Valstar © 2012