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): handle array of ids with parent refPath #14965

Merged
merged 1 commit into from
Oct 17, 2024

Conversation

vkarpov15
Copy link
Collaborator

Re: #10983

Also related to #6870, that issue addresses a slightly different case where the refPath is within the same doc array as the id.

Summary

There was a bug in our fix for #10983 where we mishandle refPath in an array of ObjectIds where the refPath refers to a parent of the array.

      const Parent = db.model(
        'Parent',
        new mongoose.Schema({
          docArray: [
            {
              type: {
                type: String,
                enum: ['Child', 'OtherModel']
              },
              ids: [
                {
                  type: mongoose.Schema.ObjectId,
                  refPath: 'docArray.type' // <-- note that `docArray.type` is not within the `ids` array
                }
              ]
            }
          ]
        })
      );

In getModelsMapForPopulate(), we end up with a case where we have a flat array of all ids and a flat array of all model names, but no way to match the two. In flat.filter((val, i) => modelNamesForRefPath[i] === modelName); we then end up accidentally filtering out incorrect ids.

Without flattening, we end up with the following list of model names:

[
  undefined, 'Child',
  'Child',   undefined,
  'Child',   undefined,
  'Child'
]

and the following ids:

[
  [],
  [
    new ObjectId('6671a008596112f0729c2045'),
    new ObjectId('667195f3596112f0728abe24'),
    new ObjectId('6671bd39596112f072cda69c'),
    new ObjectId('6672c351596112f072868565')
  ],
  [ new ObjectId('66734edd596112f0727304a2') ],
  [],
  [ new ObjectId('66726eff596112f072f8e834') ],
  [],
  [ new ObjectId('667267ff596112f072ed56b1') ]
]

We just need to correctly filter which ids belong to the child model by recursively going through the model names and ids.

Examples

@vkarpov15 vkarpov15 added this to the 8.7.2 milestone Oct 15, 2024
Copy link
Collaborator

@hasezoey hasezoey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@vkarpov15 vkarpov15 merged commit 562aabd into master Oct 17, 2024
58 checks passed
@hasezoey hasezoey deleted the vkarpov15/refpath-ids branch October 17, 2024 16:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants