Skip to content

Commit 0282f50

Browse files
committed
fix(populate): make sure to call transform with the correct index, even if no document found
Re: #14073
1 parent 965b7d5 commit 0282f50

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

lib/helpers/populate/assignVals.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,10 @@ module.exports = function assignVals(o) {
3939
const options = o.options;
4040
const count = o.count && o.isVirtual;
4141
let i;
42+
let setValueIndex = 0;
4243

4344
function setValue(val) {
45+
++setValueIndex;
4446
if (count) {
4547
return val;
4648
}
@@ -81,12 +83,13 @@ module.exports = function assignVals(o) {
8183
} else if (o.justOne === false && !Array.isArray(val)) {
8284
return valueFilter([val], options, populateOptions, _allIds);
8385
} else if (o.justOne === true && !Array.isArray(val) && Array.isArray(_allIds)) {
84-
return valueFilter(val, options, populateOptions, val == null ? val : _allIds[o.rawOrder[val._id]]);
86+
return valueFilter(val, options, populateOptions, val == null ? val : _allIds[setValueIndex - 1]);
8587
}
8688
return valueFilter(val, options, populateOptions, _allIds);
8789
}
8890

8991
for (i = 0; i < docs.length; ++i) {
92+
setValueIndex = 0;
9093
const _path = o.path.endsWith('.$*') ? o.path.slice(0, -3) : o.path;
9194
const existingVal = mpath.get(_path, docs[i], lookupLocalFields);
9295
if (existingVal == null && !getVirtual(o.originalModel.schema, _path)) {

test/model.populate.test.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10811,6 +10811,9 @@ describe('model: populate:', function() {
1081110811
for (let i = 0; i < brands.length; i++) {
1081210812
test.items.push({ name: `${i}`, brand: brands[i]._id });
1081310813
}
10814+
10815+
const id4 = new mongoose.Types.ObjectId();
10816+
test.items.push({ name: '4', brand: id4 });
1081410817
await test.save();
1081510818

1081610819
const ids = [];
@@ -10825,10 +10828,10 @@ describe('model: populate:', function() {
1082510828
}
1082610829
}
1082710830
]);
10828-
assert.equal(ids.length, 3);
10831+
assert.equal(ids.length, 4);
1082910832
assert.deepStrictEqual(
10830-
ids.map(id => id.toHexString()),
10831-
[id1.toString(), id2.toString(), id3.toString()]
10833+
ids.map(id => id?.toHexString()),
10834+
[id1.toString(), id2.toString(), id3.toString(), id4.toString()]
1083210835
);
1083310836
});
1083410837
});

0 commit comments

Comments
 (0)