Create a slug and add a slug to mongoose schema

PHOTO EMBED

Mon Jun 14 2021 12:21:17 GMT+0000 (Coordinated Universal Time)

Saved by @hisam #express #nodej #mongodb #mongoose #slug #url

// create a schema
const eventSchema = new Schema({
  name: String,
  slug: {
    type: String,
    unique: true
  },
  description: String
});

// create the model
const eventModel = mongoose.model('Event', eventSchema);

// middleware -----
// make sure that the slug is created from the name
eventSchema.pre('save', function(next) {
  this.slug = slugify(this.name);
  next();
});

// function to slugify a name
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
}
content_copyCOPY

Create a slug from a mongoose schema title (or any key really), store the slug in the title so you can use it to route route route

https://scotch.io/courses/create-a-crud-app-with-node-and-mongodb/a-mongoose-model