From 3f7dfc5ab7f227ca6eca3c9e517be20058c902e1 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 2 Sep 2021 17:54:10 -0400 Subject: [PATCH] fix(document): make `depopulate()` handle populated paths underneath document arrays Fix #10592 --- lib/document.js | 6 ++++-- test/document.test.js | 44 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/lib/document.js b/lib/document.js index c081a17335d..003156e3f7a 100644 --- a/lib/document.js +++ b/lib/document.js @@ -1368,6 +1368,8 @@ Document.prototype.$set = function $set(path, val, type, options) { this.unmarkModified(path); } } + } else { + console.log('No shouldSet', path) } if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { @@ -4203,7 +4205,7 @@ Document.prototype.depopulate = function(path) { continue; } delete populated[key]; - this.$set(key, populatedIds); + utils.setValue(key, populatedIds, this._doc); } return this; } @@ -4216,7 +4218,7 @@ Document.prototype.depopulate = function(path) { delete this.$$populatedVirtuals[singlePath]; delete this._doc[singlePath]; } else if (populatedIds) { - this.$set(singlePath, populatedIds); + utils.setValue(singlePath, populatedIds, this._doc); } } return this; diff --git a/test/document.test.js b/test/document.test.js index 1026e6abd07..e8b66176a1a 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -10484,4 +10484,48 @@ describe('document', function() { assert.ok(!doc.nested.otherProp); }); + + it('depopulate all should depopulate nested array population (gh-10592)', function() { + + const Person = db.model('Person', { + name: String + }); + + const Band = db.model('Band', { + name: String, + members: [{ type: Schema.Types.ObjectId, ref: 'Person' }], + lead: { type: Schema.Types.ObjectId, ref: 'Person' }, + embeddedMembers: [{ + active: Boolean, + member: { + type: Schema.Types.ObjectId, ref: 'Person' + } + }] + }); + + return co(function*() { + const people = [{ name: 'Axl Rose' }, { name: 'Slash' }]; + + const docs = yield Person.create(people); + let band = { + name: 'Guns N\' Roses', + members: [docs[0]._id, docs[1]], + lead: docs[0]._id, + embeddedMembers: [{ active: true, member: docs[0]._id }, { active: false, member: docs[1]._id }] + }; + band = yield Band.create(band); + yield band.populate('members lead').populate('embeddedMembers.member').execPopulate(); + assert.ok(band.populated('members')); + assert.ok(band.populated('lead')); + assert.ok(band.populated('embeddedMembers.member')); + assert.equal(band.members[0].name, 'Axl Rose'); + assert.equal(band.embeddedMembers[0].member.name, 'Axl Rose'); + band.depopulate(); + + assert.ok(!band.populated('members')); + assert.ok(!band.populated('lead')); + assert.ok(!band.populated('embeddedMembers.member')); + assert.ok(!band.embeddedMembers[0].member.name); + }); + }); });