diff --git a/lib/helpers/populate/assignRawDocsToIdStructure.js b/lib/helpers/populate/assignRawDocsToIdStructure.js index be39c370dd8..e04b601ba97 100644 --- a/lib/helpers/populate/assignRawDocsToIdStructure.js +++ b/lib/helpers/populate/assignRawDocsToIdStructure.js @@ -6,6 +6,8 @@ const utils = require('../../utils'); module.exports = assignRawDocsToIdStructure; +const kHasArray = Symbol('assignRawDocsToIdStructure.hasArray'); + /** * Assign `vals` returned by mongo query to the `rawIds` * structure returned from utils.getVals() honoring @@ -43,7 +45,16 @@ function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, re let i = 0; const len = rawIds.length; - const hasResultArrays = Object.values(resultOrder).find(o => Array.isArray(o)); + + if (sorting && recursed && options[kHasArray] === undefined) { + options[kHasArray] = false; + for (const key in resultOrder) { + if (Array.isArray(resultOrder[key])) { + options[kHasArray] = true; + break; + } + } + } for (i = 0; i < len; ++i) { id = rawIds[i]; @@ -55,7 +66,7 @@ function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, re continue; } - if (id === null && !sorting) { + if (id === null && sorting === false) { // keep nulls for findOne unless sorting, which always // removes them (backward compat) newOrder.push(id); @@ -79,7 +90,7 @@ function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, re if (doc) { if (sorting) { const _resultOrder = resultOrder[sid]; - if (hasResultArrays) { + if (options[kHasArray]) { // If result arrays, rely on the MongoDB server response for ordering newOrder.push(doc); } else {