How can I create friendly URLs with MongoDB/Node.js?

For example suppose in designing a blog application I want something like

domain.com/post/729

Instead of

domain.com/post/4f89dca9f40090d974000001

Ruby has the following

https://github.com/hakanensari/mongoid-slug

Is there an equivalent in Node.js?

There are a bunch of different projects on GitHub like https://github.com/dodo/node-slug and https://github.com/stipsan/String.Slugify.js but they focus on making valid URLs out of strings (usually the post subject or article title). I haven't seen any that take a random number and some how produce a shorter random (?) and unique number.

Personally I just have a token field on my post object that contains a unique value that is shorter than just using the DB id directly (and a tiny bit more secure). If you are using Mongoose, the token can be generated automatically by hooking the pre 'Save' event on your Mongoose model.

There are a few ways :

1- Assuming you are trying to provide a unique id to each blog post . Why not overwrite the '_id' field of your documents in the blogs collection ? Sample document would be :

{ "_id" : 122 , "content" : { "title: ..... }

You will have to look out for a method to generate an autoincrement id though, which is pretty easy. This type of primary keys are however not recommended. http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field

2- Let the _id field remain as it is, and additionaly store a key 'blogid' which is an integer, you will have to run ensureIndex on 'blogid` field though to make access by blogid fast. Storage overhead would be minor, as you will be storing a keyname and an integer more in your document.

Sample document would be :

{ "_id" : xxxxxxxxxx ,"blogid" : 122, "content" : { "title: ..... }

The id in MongoDB is actually a hexadecimal value to convert that into a numerical value you can use the following code to search for numerical value in the database like 1, 2, 3.. and this code will convert that value into appropriate hex

article_collection.db.json_serializer.ObjectID.createFromHexString(id)

where article_collection is your collection object