-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Mongoose version
8.2.1
Node.js version
20.5.1
MongoDB server version
6.3.0
Typescript version (if applicable)
No response
Description
Populating a virtual with a match() function in an embedded subdocument array inserts the populated document in the wrong array element.
In the example below, I have defined a Class
model with an array of students
where each element is a nested schema studentSchema
. I have defined another model Grade
which represents a student's grade in a class. The student schema has a grade
virtual representing the student's grade in the class (parent document).
When populating the grade
virtual, grades in the class are assigned to the incorrect student subdocument unless every student has a grade in the class.
Steps to Reproduce
The following code shows the unexpected behavior of populating a virtual with a match() function on an embedded subdocument.
const gradeSchema = new mongoose.Schema({
studentId: mongoose.Types.ObjectId,
classId: mongoose.Types.ObjectId,
grade: String,
});
const Grade = mongoose.model('Grade', 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 = mongoose.model('Class', classSchema);
const newClass = await Class.create({
name: 'History',
students: [{ name: 'Henry' }, { name: 'Robert' }],
});
const studentRobert = newClass.students.find(
({ name }) => name === 'Robert'
);
await Grade.insertMany([
{
studentId: studentRobert._id,
classId: newClass._id,
grade: 'B',
},
]);
const latestClass = await Class.findOne({ name: 'History' })
.populate('students.grade')
.select('-__v')
.exec();
// Robert's grade is populated in Henry's student object
console.log(
JSON.stringify(latestClass.toJSON({ virtuals: true }).students, null, 4)
);
Output
[
{
"name": "Henry",
"grade": {
"studentId": "660cd326a3b4ca1f9579480d",
"classId": "660cd326a3b4ca1f9579480b",
"grade": "B",
"_id": "660cd327a3b4ca1f9579480f"
},
"_id": "660cd326a3b4ca1f9579480c"
},
{
"name": "Robert",
"_id": "660cd326a3b4ca1f9579480d"
}
]
Expected Behavior
[
{
"name": "Henry",
"_id": "660cd326a3b4ca1f9579480c"
},
{
"name": "Robert",
"grade": {
"studentId": "660cd326a3b4ca1f9579480d",
"classId": "660cd326a3b4ca1f9579480b",
"grade": "B",
"_id": "660cd327a3b4ca1f9579480f"
},
"_id": "660cd326a3b4ca1f9579480d"
}
]