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

slug:{
  type: String,
  trim:true
},

Insert slug to the databse

insert.js
 

const slug_vietnamese = require('slug-vietnamese');
...
const mydata = req.body;
mydata.slug = slug_vietnamese(mydata.title);
let set = {
  $set: mydata
};
mongo_model.edit({
    _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>
 </div>
{{/each}}

Get ID from url

router

router.get('/watch/:slug?*/:id',...)

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

/id-123
/xxx/id-123
/yyy/id-123

and get id from param

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