Creating a mongoose model takes two different parts, a schema and the model.

The schema will define the parts of the object your are trying to create. For instance, if we created a blog post, it would look like:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var postSchema = new Schema({
  title:  String,
  author: String,
  body:   String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs:  Number
  }
});

In our case, for our event, we have:

Table of Contents

    // 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);

    We'll also be using middleware to have our model process something before it saves. In our case, we'll be creating a slug from the title.

    // 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
    }

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.