9/19/2017 - 5:25 PM

Friendly URLs (Express.js and Mongoose)

Friendly URLs (Express.js and Mongoose)

//Creating slugs (friendly URLs) for your website using Express.js and Mongoose

  function slugify(text) {

    return text.toString().toLowerCase()
      .replace(/\s+/g, '-')        // Replace spaces with -
      .replace(/[^\w\-]+/g, '')   // Remove all non-word chars
      .replace(/\-\-+/g, '-')      // Replace multiple - with single -
      .replace(/^-+/, '')          // Trim - from start of text
      .replace(/-+$/, '');         // Trim - from end of text

// This function takes any String and returns a slugified version—a version that replaces spaces with dashes,  removes all non-word chars, and whitespace. 
// We can then use the Mongoose pre middleware to generate the slug prior to saving each blog post.

// Generate the slug
 blogSchema.pre('save', function (next) {
    this.slug = slugify(this.title);
//end friendly URLs