Skip to content

Commit

Permalink
fix(populate): add document array subpaths to parent doc `populated()…
Browse files Browse the repository at this point in the history
…` when calling `DocumentArray#push()`

Fix #8247
  • Loading branch information
vkarpov15 committed Oct 21, 2019
1 parent 4e900eb commit a81211d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
7 changes: 1 addition & 6 deletions lib/document.js
Expand Up @@ -1130,12 +1130,7 @@ Document.prototype.$set = function $set(path, val, type, options) {

let didPopulate = false;
if (refMatches && val instanceof Document) {
if (this.ownerDocument) {
this.ownerDocument().populated(this.$__fullPath(path),
val._id, { [populateModelSymbol]: val.constructor });
} else {
this.populated(path, val._id, { [populateModelSymbol]: val.constructor });
}
this.populated(path, val._id, { [populateModelSymbol]: val.constructor });
didPopulate = true;
}

Expand Down
21 changes: 20 additions & 1 deletion lib/types/core_array.js
Expand Up @@ -628,11 +628,30 @@ class CoreMongooseArray extends Array {

_checkManualPopulation(this, arguments);

const parent = this[arrayParentSymbol];
let values = [].map.call(arguments, this._mapCast, this);
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol], undefined,
values = this[arraySchemaSymbol].applySetters(values, parent, undefined,
undefined, { skipDocumentArrayCast: true });
const ret = [].push.apply(this, values);

// If this is a document array, each element may contain single
// populated paths, so we need to modify the top-level document's
// populated cache. See gh-8247.
if (this.isMongooseDocumentArray && parent.$__.populated != null) {
const populatedPaths = Object.keys(parent.$__.populated).
filter(p => p.startsWith(this[arrayPathSymbol] + '.'));

for (const path of populatedPaths) {
const remnant = path.slice((this[arrayPathSymbol] + '.').length);
if (!Array.isArray(parent.$__.populated[path].value)) {
continue;
}
for (const val of values) {
parent.$__.populated[path].value.push(val.populated(remnant));
}
}
}

this._registerAtomic('$push', values);
this._markModified();
return ret;
Expand Down

0 comments on commit a81211d

Please sign in to comment.