Skip to content

Commit

Permalink
docs(middleware): add note about accessing the document being updated…
Browse files Browse the repository at this point in the history
… in pre('findOneAndUpdate')

Fix #8218
  • Loading branch information
vkarpov15 committed Oct 11, 2019
1 parent 327b47a commit b9c1012
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions docs/middleware.pug
Original file line number Diff line number Diff line change
Expand Up @@ -360,11 +360,22 @@ block content
**query** object rather than the document being updated.

For instance, if you wanted to add an `updatedAt` timestamp to every
`update()` call, you would use the following pre hook.
`updateOne()` call, you would use the following pre hook.

```javascript
schema.pre('update', function() {
this.update({},{ $set: { updatedAt: new Date() } });
schema.pre('updateOne', function() {
this.set({ updatedAt: new Date() });
});
```

You **cannot** access the document being updated in `pre('updateOne')` or
`pre('findOneAndUpdate')` middleware. If you need to access the document
that will be updated, you need to execute an explicit query for the document.

```javascript
schema.pre('findOneAndUpdate', async function() {
const docToUpdate = await this.model.findOne(this.getQuery());
console.log(docToUpdate); // The document that `findOneAndUpdate()` will modify
});
```

Expand Down

0 comments on commit b9c1012

Please sign in to comment.