0

A common practice in many news sites is to include both ID and slug in the URL. The ID is used to look up the actual article, and the slug is included for SEO purposes. This way, the slug can be changed to match a change in the article title without rendering useless any previous bookmarks.

Using the MongoDB ObjectId in URLs is cumbersome as it creates very very long URLs (http://www.mysite.com/article-504119a051e2726c9aa28ea1/my-article-title.html) - is there a better solution??

ACGray
  • 666
  • 3
  • 10

1 Answers1

2

You do not have to use MongoDB's default ObjectID if there is a more suitable choice for your use case. For example, you can define a custom _id field using a shorter value such as timestamp or perhaps an incrementing counter (see: How to make an auto-incrementing id field). If your use case is publishing articles and there aren't hundreds every minute, you could probably get reasonable uniqueness for an _id with a unix timestamp concatenated with a random value.

If your slugs are unique (or you could accept this restriction), you could potentially use the slug as the _id for even shorter urls. The caveat on _ids is that they cannot change, so a separately indexed slug field will give you more flexibility.

Given your goal of using slugs for SEO, you probably want to add some finesse so that there is a 302 redirect to the current "canonical url" (with correct slug field) if an alternative slug is provided. Otherwise you may incur potential SEO penalties for duplicate content if only the id portion of the url is checked.

Stennie
  • 63,885
  • 14
  • 149
  • 175