Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Middleware Hooks | Advanced Mongoose Features
MongoDB and Mongoose Essentials

Middleware Hooks

Stryg for at vise menuen

Middleware, also known as hooks, allow you to execute custom logic before or after certain operations in Mongoose. Here is a code example demonstrating both a pre-save and a post-remove middleware in a schema:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  email: String
});

// Pre-save middleware: runs before a document is saved
userSchema.pre('save', function(next) {
  // Example: convert the user's name to lowercase before saving
  this.name = this.name.toLowerCase();
  next();
});

// Post-remove middleware: runs after a document is removed
userSchema.post('remove', function(doc) {
  // Example: log the removed document's email
  console.log(`User with email ${doc.email} has been removed.`);
});

const User = mongoose.model('User', userSchema);

There are several types of middleware in Mongoose, including document middleware and query middleware. Document middleware acts on individual documents, such as save, remove, and validate. Query middleware acts on query operations like find, updateOne, or deleteMany. You can define middleware to run either before (pre) or after (post) these operations.

Middleware is useful for tasks such as:

  • Data transformation;
  • Validation;
  • Logging;
  • Triggering side effects.

In the code example above, the pre-save middleware ensures that the user's name is always stored in lowercase, while the post-remove middleware logs information after a document is deleted.

You can chain multiple middleware functions by declaring several pre or post hooks for the same event. Each middleware function calls next() to pass control to the next middleware in the chain. This allows you to modularize logic and keep your schema definitions clean and maintainable.

question mark

Which statement about Mongoose middleware is correct?

Vælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 4. Kapitel 2

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 4. Kapitel 2
some-alt