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

Unexpected population of virtual with match() function in an embedded subdocument array #14494

Closed
2 tasks done
botv opened this issue Apr 3, 2024 · 1 comment · Fixed by #14518
Closed
2 tasks done
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@botv
Copy link
Contributor

botv commented Apr 3, 2024

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"
  }
]
@vkarpov15 vkarpov15 added this to the 8.3.1 milestone Apr 4, 2024
@vkarpov15 vkarpov15 added the has repro script There is a repro script, the Mongoose devs need to confirm that it reproduces the issue label Apr 4, 2024
@IslandRhythms IslandRhythms added confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. and removed has repro script There is a repro script, the Mongoose devs need to confirm that it reproduces the issue labels Apr 5, 2024
@IslandRhythms
Copy link
Collaborator

const mongoose = require('mongoose');

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);

async function run() {
  await mongoose.connect('mongodb://localhost:27017');
  await mongoose.connection.dropDatabase();
  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)
  );
}

run();

@vkarpov15 vkarpov15 modified the milestones: 8.3.1, 8.3.2 Apr 5, 2024
vkarpov15 added a commit that referenced this issue Apr 11, 2024
fix(populate): avoid match function filtering out `null` values in populate result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants