From eb485809a49e32e743c62dee0c2a19a1145daaf2 Mon Sep 17 00:00:00 2001 From: Manik Tyagi Date: Wed, 3 Dec 2025 23:36:37 +0530 Subject: [PATCH] fix: prevent negative slice index in populate subdocPath calculation 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 --- lib/helpers/populate/getModelsMapForPopulate.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/helpers/populate/getModelsMapForPopulate.js b/lib/helpers/populate/getModelsMapForPopulate.js index 7d1b3f47fde..05d91847aeb 100644 --- a/lib/helpers/populate/getModelsMapForPopulate.js +++ b/lib/helpers/populate/getModelsMapForPopulate.js @@ -239,7 +239,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) { modelNames = [modelNameFromQuery]; // query options } else if (refPath != null) { if (typeof refPath === 'function') { - const subdocPath = options.path.slice(0, options.path.length - schema.path.length - 1); + const subdocPath = options.path.slice(0, Math.max(0, options.path.length - schema.path.length - 1)); const vals = mpath.get(subdocPath, doc, lookupLocalFields); const subdocsBeingPopulated = Array.isArray(vals) ? utils.array.flatten(vals) : @@ -301,7 +301,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) { // Ensure correct context for ref functions: subdoc, not top-level doc. See gh-8469 modelNames = new Set(); - const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1); + const subdocPath = options.path.slice(0, Math.max(0, options.path.length - schemaForCurrentDoc.path.length - 1)); const vals = mpath.get(subdocPath, doc, lookupLocalFields); const subdocsBeingPopulated = Array.isArray(vals) ? utils.array.flatten(vals) : @@ -322,7 +322,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) { } else if ((schemaForCurrentDoc = get(schema, 'options.refPath')) != null) { isRefPath = true; if (typeof refPath === 'function') { - const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1); + const subdocPath = options.path.slice(0, Math.max(0, options.path.length - schemaForCurrentDoc.path.length - 1)); const vals = mpath.get(subdocPath, doc, lookupLocalFields); const subdocsBeingPopulated = Array.isArray(vals) ? utils.array.flatten(vals) :