How to Create Unique URLs in an ExpressJS and MongoDB App

Unique URLs can be tricky sometimes if you don’t take the right route to generate one to avoid collisions. In this article, we’ll explore how you can create unique URLs easily in Express and MongoDB applications.

Note: This article assumes that you know how to build an ExpressJS app with MongoDB.

Using the Mongoose library, you will come to find that default _id is generated for each object schema value created.

In very simple terms, every endpoint which is a URL has a default id, like so:

Given an instance where you want to make your URL readable like it is like so:

There are a couple of npm packages that are helpful which you can use to implement this. Mongoose Slug Generator is one of the best and the one I use since I find it very convenient. Plus, it has super useful documentation

According to the documentation:

Mongoose plugin for creating slugs based on mongoose schema fields.

For example you can create a slug based on a document’s title and author’s name: <url>/my-post-title-kevin-roosevelt

or

unique slugs based on just the title: my-post-title-Nyiy4wW9l

How To Use:

As I said earlier, this article assumes that you already have an ExpressJS app set up with your MongoDB and already defined Mongoose Schema.
Take for example a Blog app and the schema is set up like so:

First, add the mongoose-slug-generator to the list of installed packages:

The update the Model like so:

Example Model Schema

At this point, slugs already being generated for your URLs; Now you have to set an endpoint to GET these generated URLs. Like you may have already done for getting particular posts by _id

You can define an endpoint like so:

Example Post GET slug endpoint

That is all there is to it!

When a GET request is sent to the particular endpoint, it will return the URL as defined by the slug params.

Take note of the following:
If you want, you can use more than one field in order to create a new slug field.

To create a unique slug field, you must only add the unique: true parameter in the path (also, this way the default mongo unique index gets created)

If unique is set, the plugin searches in the mongo database, and if the slug already exists in the collection, it appends to the slug a separator (default: “-”) and a random string (generated with the shortid module).

You can read more in the documentation here.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Emmanuel Odianosen

Software Developer living in Lagos, Nigeria. A Technical Writer proficient in JavaScript and Solidity.