diff --git a/lib/helpers/populate/getModelsMapForPopulate.js b/lib/helpers/populate/getModelsMapForPopulate.js index 7d1b3f47fd..05d91847ae 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) :