Repository: Automattic/mongoose (JavaScript)

Issue:
Global plugin v6.2.1 vs v6.3.0 +
### Prerequisites

- [x] I have written a descriptive issue title

### Mongoose version

6.3.0

### Node.js version

14.18.1

### MongoDB version

4.4

### Operating system

None

### Operating system version (i.e. 20.04, 11.3, 10)

_No response_

### Issue

Hi the following code behaves differently in both versions v6.2.1 and v6.3.0

```
var mongoose = require('mongoose')
mongoose.set('applyPluginsToChildSchemas', false)
 mongoose.plugin(function updateDateFields (schema, options) {
    if (!schema.path('atr')) {
      schema.add({ atr: Date })
    }
  
    schema.pre('validate', function (next) {
      console.log('validate hook called !')
      this.atr = Date.now()
      next()
    })
  })


let Schema = mongoose.Schema

var eventSchema = new Schema({
    url:  { type: String }
})


eventSchema.add({headers: {
    type: [{
      name: { type: String},
      value: { type: String},
      _id: false
    }],
    default: undefined
  }})
var Event = mongoose.model('Event', eventSchema)

var eventObj = new Event({
    url: 'google.com',
    headers: [{name: "q1", value:'1'},{name: 'Q2', value:'2'}]

});

eventObj.validate(function() {
    console.log(eventObj)
})
```
Output with v6.2.1 :

```
validate hook called !
{
  url: 'google.com',
  _id: new ObjectId("650c0f12c7358d6d47f07f79"),
  headers: [ { name: 'q1', value: '1' }, { name: 'Q2', value: '2' } ],
  atr: 2023-09-21T09:38:26.625Z
}
```

Output with v6.3.0:

```
validate hook called !
validate hook called !
validate hook called !
{
  url: 'google.com',
  _id: new ObjectId("650c0e9a8272b2309fec2b00"),
  headers: [
    { name: 'q1', value: '1', atr: 2023-09-21T09:36:26.276Z },
    { name: 'Q2', value: '2', atr: 2023-09-21T09:36:26.276Z }
  ],
  atr: 2023-09-21T09:36:26.271Z
}
```
In the v6.3.0 + version "atr" field is included in the each of sub docs also, But in my case only in the root level we need "atr" field.

Can anybody suggest how to achieve the old behaviour with the newer version. 

PS: Is this a bug?


Discussion:
Checking whether this is a bug, it looks like this change was caused by #11389 
@vkarpov15, Can you please let us know if there is any workaround for this issue?
this will be fixed with 7.5.4 (milestone), by having #13911 merged, which will be released in ~2 weeks (if the past releases is anything to go by)

if you *really* need a fix now and cant just stay on your old version until then, you can overwrite `mongoose.prototype._applyPlugins` by using [this code from the pr](https://github.com/Automattic/mongoose/blob/6304917f585b5f74a126662237d0f02da69496b4/lib/index.js#L692-L701), example:
```js
mongoose.prototype._applyPlugins = function(schema, options) {
  const _mongoose = this instanceof Mongoose ? this : mongoose;

  options = options || {};
  options.applyPluginsToDiscriminators = _mongoose.options && _mongoose.options.applyPluginsToDiscriminators || false;
  options.applyPluginsToChildSchemas = typeof (_mongoose.options && _mongoose.options.applyPluginsToChildSchemas) === 'boolean' ?
    _mongoose.options.applyPluginsToChildSchemas :
    true;
  applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied');
};
```
(overwrite this somewhere in your main mongoose entry point, before any schemas and models are created / imported)
@vkarpov15 / @hasezoey, Can you please confirm if there is any possibility to backport the issue fix to the 6.5.4 version? 

The reason for this humble request is right now we are in version 5 and to move to 7.5.4 We have to do 5->6->7 migration. Right now we are doing the 5->6 migration.
> Can you please confirm if there is any possibility to backport the issue fix to the 6.5.4 version?

it is possible, though i dont know if it is gonna be merged and when it is going to release, PR: #13945
@hasezoey, Please let us know once it's released as I can see that the PR is merged.
@vkarpov15 / @hasezoey, Can you please release the 6.12.1 so that we can migrate the mongoose from 5x to 6x.
@sakethyerra we shipped 6.12.1 earlier today :+1:



Patch:
diff --git a/lib/index.js b/lib/index.js
index 8affae77804..3e7bf3709ef 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -694,7 +694,9 @@ Mongoose.prototype._applyPlugins = function(schema, options) {
 
   options = options || {};
   options.applyPluginsToDiscriminators = _mongoose.options && _mongoose.options.applyPluginsToDiscriminators || false;
-  options.applyPluginsToChildSchemas = typeof (_mongoose.options && _mongoose.options.applyPluginsToDiscriminators) === 'boolean' ? _mongoose.options.applyPluginsToDiscriminators : true;
+  options.applyPluginsToChildSchemas = typeof (_mongoose.options && _mongoose.options.applyPluginsToChildSchemas) === 'boolean' ?
+    _mongoose.options.applyPluginsToChildSchemas :
+    true;
   applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied');
 };
 


Test patch:
diff --git a/test/index.test.js b/test/index.test.js
index 0976aab3479..d20b8c051f8 100644
--- a/test/index.test.js
+++ b/test/index.test.js
@@ -429,6 +429,25 @@ describe('mongoose module:', function() {
     return Promise.resolve();
   });
 
+  it('global plugins with applyPluginsToChildSchemas (gh-13887)', function() {
+    const m = new Mongoose();
+    m.set('applyPluginsToChildSchemas', false);
+
+    const called = [];
+    m.plugin(function(s) {
+      called.push(s);
+    });
+
+    const schema = new m.Schema({
+      subdoc: new m.Schema({ name: String }),
+      arr: [new m.Schema({ name: String })]
+    });
+
+    m.model('Test', schema);
+    assert.equal(called.length, 1);
+    assert.ok(called.indexOf(schema) !== -1);
+  });
+
   it('global plugins recompile schemas (gh-7572)', function() {
     function helloPlugin(schema) {
       schema.virtual('greeting').get(() => 'hello');