Skip to content

Conversation

@maniktyagi04
Copy link

Description

This PR fixes a bug where calculating subdocPath in populate operations could result in negative slice indices, causing incorrect path calculations.

Fixes #15861

Problem

In lib/helpers/populate/getModelsMapForPopulate.js, lines 242, 304, and 325 use:

const subdocPath = options.path.slice(0, options.path.length - schema.path.length - 1);

If schema.path.length + 1 >= options.path.length, the second argument becomes negative, causing slice() to count from the end instead of the beginning.

Solution

Added Math.max(0, ...) to ensure the slice index never goes negative:

const subdocPath = options.path.slice(0, Math.max(0, options.path.length - schema.path.length - 1));

Changes

  • Fixed line 242: Added Math.max(0, ...) wrapper
  • Fixed line 304: Added Math.max(0, ...) wrapper
  • Fixed line 325: Added Math.max(0, ...) wrapper

Testing

  • All existing populate tests pass (305 tests in test/model.populate.test.js)
  • Lint passes (npm run lint)

Impact

This fix prevents incorrect subdocPath calculations in edge cases where the schema path is longer than or equal to the options path, ensuring populate operations work correctly in all scenarios.

When calculating subdocPath in populate operations, if schema.path.length + 1
is greater than or equal to options.path.length, the slice operation would
result in a negative index, causing incorrect path calculations.

This fix adds Math.max(0, ...) to ensure the slice index never goes negative,
preventing the slice() method from counting from the end of the string.

Fixes three occurrences on lines 242, 304, and 325 in
lib/helpers/populate/getModelsMapForPopulate.js
Copy link
Collaborator

@AbdelrahmanHafez AbdelrahmanHafez left a comment

Choose a reason for hiding this comment

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

Can you please write a test case that fails without this change, so that we can prevent regressions in the future?
Also helps understand with code what the issue you're facing looks like.

@AbdelrahmanHafez AbdelrahmanHafez added the needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity label Dec 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Negative slice index in populate subdocPath calculation

2 participants