Skip to content

Commit

Permalink
Merge pull request #12867 from Automattic/perf-assignRawDocsToIdStruc…
Browse files Browse the repository at this point in the history
…ture

improve performance of assignRawDocsToIdStructure
  • Loading branch information
vkarpov15 committed Jan 6, 2023
2 parents e9b5eed + c07fef4 commit 6043907
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions lib/helpers/populate/assignRawDocsToIdStructure.js
Expand Up @@ -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
Expand Down Expand Up @@ -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];
Expand All @@ -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);
Expand All @@ -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 {
Expand Down

0 comments on commit 6043907

Please sign in to comment.