Skip to content

fix(populate): handle array of ids with parent refPath#14965

Merged
vkarpov15 merged 1 commit intomasterfrom
vkarpov15/refpath-ids
Oct 17, 2024
Merged

fix(populate): handle array of ids with parent refPath#14965
vkarpov15 merged 1 commit intomasterfrom
vkarpov15/refpath-ids

Conversation

@vkarpov15
Copy link
Copy Markdown
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
Copy Markdown
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
@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