Skip to content

Commit

Permalink
Merge pull request Automattic#12804 from Automattic/vkarpov15/Automat…
Browse files Browse the repository at this point in the history
…ticgh-12739

fix(populate): avoid calling `transform` if there's no populate results and using lean
  • Loading branch information
vkarpov15 committed Dec 16, 2022
2 parents dfd5eeb + 24da2a4 commit 7fbb440
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/helpers/populate/assignVals.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@ function valueFilter(val, assignmentOpts, populateOptions, allIds) {
const _allIds = Array.isArray(allIds) ? allIds[i] : allIds;
if (!isPopulatedObject(subdoc) && (!populateOptions.retainNullValues || subdoc != null) && !userSpecifiedTransform) {
continue;
} else if (!populateOptions.retainNullValues && subdoc == null) {
continue;
} else if (userSpecifiedTransform) {
subdoc = transform(isPopulatedObject(subdoc) ? subdoc : null, _allIds);
}
Expand Down
30 changes: 29 additions & 1 deletion test/model.populate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9942,7 +9942,6 @@ describe('model: populate:', function() {

const Child = db.model('Child', Schema({ name: String }));


const children = await Child.create([{ name: 'Luke' }, { name: 'Leia' }]);
let p = await Parent.create({
name: 'Anakin',
Expand Down Expand Up @@ -10024,6 +10023,35 @@ describe('model: populate:', function() {
assert.equal(called[0].id.toHexString(), newId.toHexString());
});

it('avoids calling `transform()` with `lean()` when no results (gh-12739)', async function() {
const parentSchema = new Schema({ title: String });
const childSchema = new Schema({
title: String,
parent: { type: mongoose.Schema.Types.ObjectId, ref: 'Parent' }
});
parentSchema.virtual('children', {
ref: 'Child',
localField: '_id',
foreignField: 'parent'
});
const Parent = db.model('Parent', parentSchema);
const Child = db.model('Child', childSchema);

await Parent.create({ title: 'parent' });
await Child.create({ title: 'child' });
const p = await Parent.find().lean().populate({
path: 'children',
match: { title: 'child' },
select: '-__v',
strictPopulate: false,
transform: doc => {
return doc;
}
});
assert.equal(p.length, 1);
assert.deepStrictEqual(p[0].children, []);
});

it('transform to primitive (gh-10064)', async function() {
const Child = db.model('Child', mongoose.Schema({ name: String }));
const Parent = db.model('Parent', mongoose.Schema({
Expand Down

0 comments on commit 7fbb440

Please sign in to comment.