Skip to content

Bug: Negative slice index in populate subdocPath calculation #15861

@maniktyagi04

Description

@maniktyagi04

Description

When calculating subdocPath in populate operations with nested paths, if schema.path.length + 1 is greater than or equal to options.path.length, the slice operation results in a negative index. This causes slice() to count from the end of the string instead of the beginning, leading to incorrect path calculations.

Affected Code

lib/helpers/populate/getModelsMapForPopulate.js - Lines 242, 304, and 325

Current Behavior

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

When schema.path.length + 1 >= options.path.length, the second argument becomes negative or zero, causing incorrect subdocPath extraction.

Expected Behavior

The slice index should never be negative. The subdocPath should be correctly extracted even in edge cases where the schema path is longer than or equal to the options path.

Proposed Fix

Add Math.max(0, ...) to prevent negative indices:

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

Impact

This bug affects populate operations with nested paths and could cause populate to fail or use incorrect paths in edge cases.

Testing

All existing populate tests pass with this fix (305 tests in test/model.populate.test.js).

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions