Skip to content

Commit b9c1012

Browse files
committed
docs(middleware): add note about accessing the document being updated in pre('findOneAndUpdate')
Fix #8218
1 parent 327b47a commit b9c1012

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

docs/middleware.pug

+14-3
Original file line numberDiff line numberDiff line change
@@ -360,11 +360,22 @@ block content
360360
**query** object rather than the document being updated.
361361

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

365365
```javascript
366-
schema.pre('update', function() {
367-
this.update({},{ $set: { updatedAt: new Date() } });
366+
schema.pre('updateOne', function() {
367+
this.set({ updatedAt: new Date() });
368+
});
369+
```
370+
371+
You **cannot** access the document being updated in `pre('updateOne')` or
372+
`pre('findOneAndUpdate')` middleware. If you need to access the document
373+
that will be updated, you need to execute an explicit query for the document.
374+
375+
```javascript
376+
schema.pre('findOneAndUpdate', async function() {
377+
const docToUpdate = await this.model.findOne(this.getQuery());
378+
console.log(docToUpdate); // The document that `findOneAndUpdate()` will modify
368379
});
369380
```
370381

0 commit comments

Comments
 (0)