Skip to content

Commit a81211d

Browse files
committed
fix(populate): add document array subpaths to parent doc populated() when calling DocumentArray#push()
Fix #8247
1 parent 4e900eb commit a81211d

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

lib/document.js

+1-6
Original file line numberDiff line numberDiff line change
@@ -1130,12 +1130,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
11301130

11311131
let didPopulate = false;
11321132
if (refMatches && val instanceof Document) {
1133-
if (this.ownerDocument) {
1134-
this.ownerDocument().populated(this.$__fullPath(path),
1135-
val._id, { [populateModelSymbol]: val.constructor });
1136-
} else {
1137-
this.populated(path, val._id, { [populateModelSymbol]: val.constructor });
1138-
}
1133+
this.populated(path, val._id, { [populateModelSymbol]: val.constructor });
11391134
didPopulate = true;
11401135
}
11411136

lib/types/core_array.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -628,11 +628,30 @@ class CoreMongooseArray extends Array {
628628

629629
_checkManualPopulation(this, arguments);
630630

631+
const parent = this[arrayParentSymbol];
631632
let values = [].map.call(arguments, this._mapCast, this);
632-
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol], undefined,
633+
values = this[arraySchemaSymbol].applySetters(values, parent, undefined,
633634
undefined, { skipDocumentArrayCast: true });
634635
const ret = [].push.apply(this, values);
635636

637+
// If this is a document array, each element may contain single
638+
// populated paths, so we need to modify the top-level document's
639+
// populated cache. See gh-8247.
640+
if (this.isMongooseDocumentArray && parent.$__.populated != null) {
641+
const populatedPaths = Object.keys(parent.$__.populated).
642+
filter(p => p.startsWith(this[arrayPathSymbol] + '.'));
643+
644+
for (const path of populatedPaths) {
645+
const remnant = path.slice((this[arrayPathSymbol] + '.').length);
646+
if (!Array.isArray(parent.$__.populated[path].value)) {
647+
continue;
648+
}
649+
for (const val of values) {
650+
parent.$__.populated[path].value.push(val.populated(remnant));
651+
}
652+
}
653+
}
654+
636655
this._registerAtomic('$push', values);
637656
this._markModified();
638657
return ret;

0 commit comments

Comments
 (0)