diff --git a/lib/schema/documentarray.js b/lib/schema/documentarray.js index b9066921cb9..86664af7801 100644 --- a/lib/schema/documentarray.js +++ b/lib/schema/documentarray.js @@ -130,12 +130,12 @@ function _createConstructor(schema, options, baseClass) { Subdocument || (Subdocument = require('../types/ArraySubdocument')); // compile an embedded document for this schema - function EmbeddedDocument(_value, parentArray) { + function EmbeddedDocument() { Subdocument.apply(this, arguments); - if (parentArray == null || parentArray.getArrayParent() == null) { + if (this.__parentArray == null || this.__parentArray.getArrayParent() == null) { return; } - this.$session(parentArray.getArrayParent().$session()); + this.$session(this.__parentArray.getArrayParent().$session()); } schema._preCompile(); diff --git a/test/model.update.test.js b/test/model.update.test.js index 7638989c7a6..84203e90841 100644 --- a/test/model.update.test.js +++ b/test/model.update.test.js @@ -2023,6 +2023,37 @@ describe('model: update:', function() { catch(done); }); + it('handles $set on document array in discriminator with runValidators (gh-12518)', async function() { + const options = { discriminatorKey: 'kind', runValidators: true }; + + const countrySchema = new mongoose.Schema({ title: String }, options); + const areasSubSchema = new mongoose.Schema({ country: [countrySchema] }, options); + const WorldSchema = new mongoose.Schema({ areas: areasSubSchema }, options); + + const World = db.model( + 'World', + new mongoose.Schema({ title: String }, options) + ); + const Earth = World.discriminator('Earth', WorldSchema); + + const data = { + areas: { + country: [ + { + title: 'titlec' + } + ] + } + }; + await Earth.updateOne( + { _id: mongoose.Types.ObjectId() }, + data, + { + runValidators: true + } + ); + }); + it('single nested schema with geo (gh-4465)', function(done) { const addressSchema = new Schema({ geo: { type: [Number], index: '2dsphere' }