Aquasar
  • Home
  • Portfolio
  • Articles
  • Pricing
  • About
  • Contact
WEB DEVELOPMENT |SEO |DIGITAL ADS

Document Middleware with Mongoose

Aug 8th, 2019

Alex Quasar

mongo

Document middleware in Mongoose

Using `pre` middleware

Using `pre` middleware aka (hooks) allow us to to specify what we want to do before a certain event takes place. An example of an event could be saving or creating a document.

Here is an example of what is called a `pre-save hook`:

// DOCUMENT MIDDLEWARE -- runs before .save() and .create() // pre save hooks
TourSchema.pre('save', function(next) {
    this.slug = slugify(this.name, { lower: true });
    next();
})

Note: The this keyword is pointing to the document

Using `post` middleware

Using `post` middleware aka (hooks) allows us to specify what we to do after a certain event has occurred.