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

fix(populate): avoid match function filtering out null values in populate result #14518

Merged
merged 1 commit into from Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions lib/helpers/populate/assignVals.js
Expand Up @@ -101,8 +101,8 @@ module.exports = function assignVals(o) {
valueToSet = numDocs(rawIds[i]);
} else if (Array.isArray(o.match)) {
valueToSet = Array.isArray(rawIds[i]) ?
rawIds[i].filter(sift(o.match[i])) :
[rawIds[i]].filter(sift(o.match[i]))[0];
rawIds[i].filter(v => v == null || sift(o.match[i])(v)) :
[rawIds[i]].filter(v => v == null || sift(o.match[i])(v))[0];
} else {
valueToSet = rawIds[i];
}
Expand Down
53 changes: 53 additions & 0 deletions test/model.populate.test.js
Expand Up @@ -10968,4 +10968,57 @@ describe('model: populate:', function() {
assert.equal(res.children[0].subdoc.name, 'A');
assert.equal(res.children[1].subdoc.name, 'B');
});

it('avoids filtering out `null` values when applying match function (gh-14494)', async function() {
const gradeSchema = new mongoose.Schema({
studentId: mongoose.Types.ObjectId,
classId: mongoose.Types.ObjectId,
grade: String
});

const Grade = db.model('Test', gradeSchema);

const studentSchema = new mongoose.Schema({
name: String
});

studentSchema.virtual('grade', {
ref: Grade,
localField: '_id',
foreignField: 'studentId',
match: (doc) => ({
classId: doc._id
}),
justOne: true
});

const classSchema = new mongoose.Schema({
name: String,
students: [studentSchema]
});

const Class = db.model('Test2', classSchema);

const newClass = await Class.create({
name: 'History',
students: [{ name: 'Henry' }, { name: 'Robert' }]
});

const studentRobert = newClass.students.find(
({ name }) => name === 'Robert'
);

await Grade.create({
studentId: studentRobert._id,
classId: newClass._id,
grade: 'B'
});

const latestClass = await Class.findOne({ name: 'History' }).populate('students.grade');

assert.equal(latestClass.students[0].name, 'Henry');
assert.equal(latestClass.students[0].grade, null);
assert.equal(latestClass.students[1].name, 'Robert');
assert.equal(latestClass.students[1].grade.grade, 'B');
});
});