From 56563ec8d300437b0dcd487695f49eadd5eefcaf Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 20 Jun 2023 14:42:21 -0400 Subject: [PATCH] docs(middleware): explain how to access query and save() parameters in middleware Fix #13498 --- docs/middleware.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/middleware.md b/docs/middleware.md index f7b37301233..3a2c7cd9072 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -12,6 +12,7 @@ on the schema level and is useful for writing [plugins](plugins.html).
  • Asynchronous Post Hooks
  • Define Middleware Before Compiling Models
  • Save/Validate Hooks
  • +
  • Accessing Parameters in Middleware
  • Naming Conflicts
  • Notes on findAndUpdate() and Query Middleware
  • Error Handling Middleware
  • @@ -344,6 +345,39 @@ schema.post('save', function() { }); ``` +

    Accessing Parameters in Middleware

    + +Mongoose provides 2 ways to get information about the function call that triggered the middleware. +For query middleware, we recommend using `this`, which will be a [Mongoose Query instance](api/query.html). + +```javascript +const userSchema = new Schema({ name: String, age: Number }); +userSchema.pre('findOneAndUpdate', function() { + console.log(this.getFilter()); // { name: 'John' } + console.log(this.getUpdate()); // { age: 30 } +}); +const User = mongoose.model('User', userSchema); + +await User.findOneAndUpdate({ name: 'John' }, { $set: { age: 30 } }); +``` + +For document middleware, like `pre('save')`, Mongoose passes the 1st parameter to `save()` as the 2nd argument to your `pre('save')` callback. +You should use the 2nd argument to get access to the `save()` call's `options`, because Mongoose documents don't store all the options you can pass to `save()`. + +```javascript +const userSchema = new Schema({ name: String, age: Number }); +userSchema.pre('save', function(next, options) { + options.validateModifiedOnly; // true + + // Remember to call `next()` unless you're using an async function or returning a promise + next(); +}); +const User = mongoose.model('User', userSchema); + +const doc = new User({ name: 'John', age: 30 }); +await doc.save({ validateModifiedOnly: true }); +``` +

    Naming Conflicts

    Mongoose has both query and document hooks for `remove()`.