From 4258642b233b379f7e88cf4eb5b792370ee6fd6a Mon Sep 17 00:00:00 2001 From: Luca Pizzini Date: Tue, 29 Nov 2022 09:25:06 +0100 Subject: [PATCH] docs(middleware): added note about execution policy on subdocuments fix #12694 --- docs/middleware.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/middleware.md b/docs/middleware.md index d6c016108a7..67d1282f1c0 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -85,6 +85,26 @@ This means that both `doc.updateOne()` and `Model.updateOne()` trigger **Note:** The [`create()`](api.html#model_Model-create) function fires `save()` hooks. +**Note:** Query middlewares are not executed on subdocuments. + +```javascript +const childSchema = new mongoose.Schema({ + name: String +}); + +const mainSchema = new mongoose.Schema({ + child: [childSchema] +}); + +mainSchema.pre('findOneAndUpdate', function () { + console.log('Middleware on parent document'); // Will be executed +}); + +childSchema.pre('findOneAndUpdate', function () { + console.log('Middleware on subdocument'); // Will not be executed +}); +``` +

Pre

Pre middleware functions are executed one after another, when each