Skip to content

Commit 516464a

Browse files
authored
Merge pull request #14686 from Automattic/vkarpov15/gh-14680
fix(projection): handle projections on arrays in `Model.hydrate()` projection option
2 parents c062b1f + 36ea383 commit 516464a

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

lib/helpers/projection/applyProjection.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ function applyExclusiveProjection(doc, projection, hasIncludedChildren, projecti
3535
if (doc == null || typeof doc !== 'object') {
3636
return doc;
3737
}
38+
if (Array.isArray(doc)) {
39+
return doc.map(el => applyExclusiveProjection(el, projection, hasIncludedChildren, projectionLimb, prefix));
40+
}
3841
const ret = { ...doc };
3942
projectionLimb = prefix ? (projectionLimb || {}) : projection;
4043

@@ -57,6 +60,9 @@ function applyInclusiveProjection(doc, projection, hasIncludedChildren, projecti
5760
if (doc == null || typeof doc !== 'object') {
5861
return doc;
5962
}
63+
if (Array.isArray(doc)) {
64+
return doc.map(el => applyInclusiveProjection(el, projection, hasIncludedChildren, projectionLimb, prefix));
65+
}
6066
const ret = { ...doc };
6167
projectionLimb = prefix ? (projectionLimb || {}) : projection;
6268

test/helpers/projection.applyProjection.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,15 @@ describe('applyProjection', function() {
2121
assert.deepEqual(applyProjection(obj, { 'nested.str2': 0 }), { str: 'test', nested: { num3: 42 } });
2222
assert.deepEqual(applyProjection(obj, { nested: { num3: 0 } }), { str: 'test', nested: { str2: 'test2' } });
2323
});
24+
25+
it('handles projections underneath arrays (gh-14680)', function() {
26+
const obj = {
27+
_id: 12,
28+
testField: 'foo',
29+
testArray: [{ _id: 42, field1: 'bar' }]
30+
};
31+
32+
assert.deepEqual(applyProjection(obj, { 'testArray.field1': 1 }), { testArray: [{ field1: 'bar' }] });
33+
assert.deepEqual(applyProjection(obj, { 'testArray.field1': 0, _id: 0 }), { testField: 'foo', testArray: [{ _id: 42 }] });
34+
});
2435
});

0 commit comments

Comments
 (0)