Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #8317 map(...) #8351

Merged
merged 7 commits into from Nov 19, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 18 additions & 9 deletions lib/types/documentarray.js
Expand Up @@ -180,6 +180,15 @@ class CoreDocumentArray extends CoreMongooseArray {
return arr;
}

map() {
const arr = super.map.apply(this,arguments);

arr[arrayParentSymbol] = this[arrayParentSymbol];
arr[arrayPathSymbol] = this[arrayPathSymbol];

return arr;
}

/**
* Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
*
Expand Down Expand Up @@ -328,18 +337,18 @@ if (util.inspect.custom) {

function _updateParentPopulated(arr) {
const parent = arr[arrayParentSymbol];
if (parent.$__.populated != null) {
const populatedPaths = Object.keys(parent.$__.populated).
filter(p => p.startsWith(arr[arrayPathSymbol] + '.'));
if (parent.$__.populated == null) return;

for (const path of populatedPaths) {
const remnant = path.slice((arr[arrayPathSymbol] + '.').length);
if (!Array.isArray(parent.$__.populated[path].value)) {
continue;
}
const populatedPaths = Object.keys(parent.$__.populated).
filter(p => p.startsWith(arr[arrayPathSymbol] + '.'));

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

parent.$__.populated[path].value = arr.map(val => val.populated(remnant));
}
}

Expand Down
14 changes: 14 additions & 0 deletions test/types.documentarray.test.js
Expand Up @@ -575,6 +575,20 @@ describe('types.documentarray', function() {
assert.equal(arr.length, 1);
assert.equal(doc.docs.length, 2);
});

it('map() copies parent and path ()', function() {
const personSchema = new Schema({ friends: [{ name: { type: String } }]});
const Person = mongoose.model('gh8317-map', personSchema);

const person = new Person({ friends: [{ name: 'Hafez' }] });

const friendsNames = person.friends.map(friend => friend.name);

friendsNames.push('Sam');

assert.equal(friendsNames.length, 2);
assert.equal(friendsNames[1], 'Sam');
});
});

it('cleans modified subpaths on splice() (gh-7249)', function() {
Expand Down