Skip to content

Commit

Permalink
fix(projection): handle projections on arrays in Model.hydrate() pr…
Browse files Browse the repository at this point in the history
…ojection option

Fix #14680
  • Loading branch information
vkarpov15 committed Jun 24, 2024
1 parent 3ad5b4f commit 36ea383
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/helpers/projection/applyProjection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;

Expand Down
11 changes: 11 additions & 0 deletions test/helpers/projection.applyProjection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }] });
});
});

0 comments on commit 36ea383

Please sign in to comment.