Querying a post by date (year and month) and slug
Problem
I am attempting to create a blog system using Node.js and Express.
Each article
has a slug, which is saved into the database. For example, hello-world
. Currently I can access a post with just it's slug, such as /article/hello-world
.
However, I want the URLs to look more like this: /article/:year/:month/:slug
. For example, /article/2011/07/hello-world
. How would I do this? I am using MongoDB's findOne
method currently, and in the database I have saved a timestamp in a field called created_at
.
Solution
You can do a date range query:
db. article.findOne({
created_at: { $gte: ISODate("2012-04-01"), $lte: ISODate("2012-04-30") },
slug: "hello-world"
})
Your specific client language (node.js in this case) I'm sure provides easier ways to work with the date objects.
Discussion
View additional discussion.