Skip to content

Commit

Permalink
docs(middleware): clarify that query middleware applies to document b…
Browse files Browse the repository at this point in the history
…y default

Fix #13713
  • Loading branch information
vkarpov15 committed Aug 14, 2023
1 parent 392f9fa commit f20cd2c
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions docs/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,28 @@ schema.pre('deleteOne', { query: true, document: false }, function() {
});
```

Mongoose also has both query and document hooks for `validate()`.
Unlike `deleteOne` and `updateOne`, `validate` middleware applies to `Document.prototype.validate` by default.

```javascript
const schema = new mongoose.Schema({ name: String });
schema.pre('validate', function() {
console.log('Document validate');
});
schema.pre('validate', { query: true, document: false }, function() {
console.log('Query validate');
});
const Test = mongoose.model('Test', schema);

const doc = new Test({ name: 'foo' });

// Prints "Document validate"
await doc.validate();

// Prints "Query validate"
await Test.find().validate();
```

<h2 id="notes"><a href="#notes">Notes on findAndUpdate() and Query Middleware</a></h2>

Pre and post `save()` hooks are **not** executed on `update()`,
Expand Down

0 comments on commit f20cd2c

Please sign in to comment.