From 36ea38302d0c502a41371e484dc67f2a229f4fa4 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 24 Jun 2024 12:40:41 -0400 Subject: [PATCH] fix(projection): handle projections on arrays in `Model.hydrate()` projection option Fix #14680 --- lib/helpers/projection/applyProjection.js | 6 ++++++ test/helpers/projection.applyProjection.test.js | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/lib/helpers/projection/applyProjection.js b/lib/helpers/projection/applyProjection.js index 1552e07e686..7a35b128b24 100644 --- a/lib/helpers/projection/applyProjection.js +++ b/lib/helpers/projection/applyProjection.js @@ -35,6 +35,9 @@ function applyExclusiveProjection(doc, projection, hasIncludedChildren, projecti if (doc == null || typeof doc !== 'object') { return doc; } + if (Array.isArray(doc)) { + return doc.map(el => applyExclusiveProjection(el, projection, hasIncludedChildren, projectionLimb, prefix)); + } const ret = { ...doc }; projectionLimb = prefix ? (projectionLimb || {}) : projection; @@ -57,6 +60,9 @@ function applyInclusiveProjection(doc, projection, hasIncludedChildren, projecti if (doc == null || typeof doc !== 'object') { return doc; } + if (Array.isArray(doc)) { + return doc.map(el => applyInclusiveProjection(el, projection, hasIncludedChildren, projectionLimb, prefix)); + } const ret = { ...doc }; projectionLimb = prefix ? (projectionLimb || {}) : projection; diff --git a/test/helpers/projection.applyProjection.test.js b/test/helpers/projection.applyProjection.test.js index fadfe53fa25..e73d0d657ee 100644 --- a/test/helpers/projection.applyProjection.test.js +++ b/test/helpers/projection.applyProjection.test.js @@ -21,4 +21,15 @@ describe('applyProjection', function() { assert.deepEqual(applyProjection(obj, { 'nested.str2': 0 }), { str: 'test', nested: { num3: 42 } }); assert.deepEqual(applyProjection(obj, { nested: { num3: 0 } }), { str: 'test', nested: { str2: 'test2' } }); }); + + it('handles projections underneath arrays (gh-14680)', function() { + const obj = { + _id: 12, + testField: 'foo', + testArray: [{ _id: 42, field1: 'bar' }] + }; + + assert.deepEqual(applyProjection(obj, { 'testArray.field1': 1 }), { testArray: [{ field1: 'bar' }] }); + assert.deepEqual(applyProjection(obj, { 'testArray.field1': 0, _id: 0 }), { testField: 'foo', testArray: [{ _id: 42 }] }); + }); });