Skip to content

Commit

Permalink
Merge pull request #13734 from Automattic/vkarpov15/gh-13713
Browse files Browse the repository at this point in the history
docs(middleware): clarify that query middleware applies to document by default
  • Loading branch information
vkarpov15 committed Aug 15, 2023
2 parents 392f9fa + f20cd2c commit 85f2b2a
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 85f2b2a

Please sign in to comment.