Middleware Hooks
Desliza para mostrar el menú
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.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla