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:
<url>/id
e.g
http://localhost:3000/posts/5e3f771fb3d6e8538acf97b7
Given an instance where you want to make your URL readable like it is like so:
<url>/posts/post-title-1
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:
const mongoose = require('mongoose');
const postSchema = mongoose.Schema({
title: String,
body: String
})postSchema.set('timestamps', true);
module.exports = mongoose.model('Posts', postSchema);
First, add the mongoose-slug-generator to the list of installed packages:
npm install mongoose-slug-generator --save
The update the Model like so:
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:
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.
...
slug: { type: String, slug: ["title", "subtitle"] }
...
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)
...
slug: { type: String, slug: ["title", "subtitle"], unique: true }
...
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.