URL Slug with Nodejs

2 months ago

In this post we will deep dive about slug url in nodejs mongodb

Generate slug on fly or store on db?

Generate slug on the fly is also a good idea but I store slug on db.

Simply add 1 field on the mongoodb schame

  type: String,

Insert slug to the databse


const slug_vietnamese = require('slug-vietnamese');
const mydata = req.body;
mydata.slug = slug_vietnamese(mydata.title);
let set = {
  $set: mydata
    _id: id
  }, set, function(err, data) {
      // ...

The slug-vietnamese module will convert your title to url validate format by remove unwanted part example space, special character...

const slug_vietnamese = require('slug-vietnamese');

console.log(slug_vietnamese(`Cao tốc Đà Nẵng - Quảng Ngãi.`));
// cao-toc-da-nang-quang-ngai

Show list of products

{{#each data}}
 <div class="my_list">
    <a href="/read/{{slug}}/{{_id}}">{{title}}</a>

Get ID from url



the parterm slug?* mean that the slug param it is optinal and it can by anything.
so all of these url is the same.


and get id from param

const id = req.params.id || null;
// process get data by id