Skip to content

Commit

Permalink
fix(document): make depopulate() handle populated paths underneath …
Browse files Browse the repository at this point in the history
…document arrays

Fix #10592
  • Loading branch information
vkarpov15 committed Sep 2, 2021
1 parent b34d1d5 commit 3f7dfc5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/document.js
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
Expand Down
44 changes: 44 additions & 0 deletions test/document.test.js
Expand Up @@ -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);
});
});
});

0 comments on commit 3f7dfc5

Please sign in to comment.