Skip to content

Commit f552fe2

Browse files
authored
Merge pull request #13842 from Automattic/vkarpov15/gh-13839
Edits to Handle null objects in arrays during populate operations
2 parents 41de90c + e42aaaf commit f552fe2

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lib/helpers/populate/markArraySubdocsPopulated.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ module.exports = function markArraySubdocsPopulated(doc, populated) {
3838

3939
if (utils.isMongooseDocumentArray(val)) {
4040
for (let j = 0; j < val.length; ++j) {
41-
val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item);
41+
if (val[j]) {
42+
val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item);
43+
}
4244
}
4345
break;
4446
}

test/model.populate.test.js

+22
Original file line numberDiff line numberDiff line change
@@ -10285,6 +10285,28 @@ describe('model: populate:', function() {
1028510285

1028610286
});
1028710287

10288+
it('handles populating underneath document arrays that have null (gh-13839)', async function() {
10289+
const schema = new Schema({
10290+
children: [
10291+
{
10292+
doc: { type: mongoose.Schema.Types.ObjectId, ref: 'Child' },
10293+
name: String
10294+
}
10295+
]
10296+
});
10297+
const Parent = db.model('Parent', schema);
10298+
const Child = db.model('Child', new Schema({ name: String }));
10299+
10300+
const child = new Child({ name: 'gh-13839-test' });
10301+
await child.save();
10302+
let parent = new Parent({ children: [{ doc: child._id, name: 'foo' }, null] });
10303+
await parent.save();
10304+
10305+
parent = await Parent.findById(parent._id).populate('children.doc');
10306+
assert.equal(parent.children.length, 2);
10307+
assert.equal(parent.children[0].doc.name, 'gh-13839-test');
10308+
assert.equal(parent.children[1], null);
10309+
});
1028810310

1028910311
describe('strictPopulate', function() {
1029010312
it('reports full path when throwing `strictPopulate` error with deep populate (gh-10923)', async function() {

0 commit comments

Comments
 (0)