From b9c10123dee0ed9dad176b018552bb3004ed2535 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Fri, 11 Oct 2019 11:31:44 -0400 Subject: [PATCH] docs(middleware): add note about accessing the document being updated in pre('findOneAndUpdate') Fix #8218 --- docs/middleware.pug | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/middleware.pug b/docs/middleware.pug index 1b5cf0afd4a..6b326fd4b14 100644 --- a/docs/middleware.pug +++ b/docs/middleware.pug @@ -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 }); ```