diff --git a/lib/types/documentarray.js b/lib/types/documentarray.js index 87757e4f171..b9cc33cd24d 100644 --- a/lib/types/documentarray.js +++ b/lib/types/documentarray.js @@ -328,18 +328,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 || 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)); } } diff --git a/test/types.documentarray.test.js b/test/types.documentarray.test.js index 1a148714750..8140ee484b0 100644 --- a/test/types.documentarray.test.js +++ b/test/types.documentarray.test.js @@ -575,6 +575,19 @@ describe('types.documentarray', function() { assert.equal(arr.length, 1); assert.equal(doc.docs.length, 2); }); + + it('map() works', 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() {