Skip to content

Commit

Permalink
Merge pull request #14686 from Automattic/vkarpov15/gh-14680
Browse files Browse the repository at this point in the history
fix(projection): handle projections on arrays in `Model.hydrate()` projection option
  • Loading branch information
vkarpov15 authored Jun 25, 2024
2 parents c062b1f + 36ea383 commit 516464a
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 516464a

Please sign in to comment.