Skip to content

Commit 0bc78dd

Browse files
committed
fix(ProjectionHelper): Avoid flatting for MongoDB Projection Operators
https://docs.mongodb.com/v3.2/reference/operator/projection/meta/
1 parent 01098ab commit 0bc78dd

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

src/resolvers/helpers/__tests__/projection-test.js

+28
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,38 @@ describe('Resolver helper `projection` ->', () => {
2121
projectionHelper(resolveParams);
2222
expect(spyFn).to.have.not.been.called();
2323
});
24+
2425
it('should call query.select if projection is provided', () => {
2526
resolveParams.projection = { name: 1, age: 1 };
2627
projectionHelper(resolveParams);
2728
expect(spyFn).to.have.been.called.with({ name: true, age: true });
2829
});
30+
31+
it('should make projection fields flat', () => {
32+
resolveParams.projection = { name: { first: 1, last: 1 } };
33+
projectionHelper(resolveParams);
34+
expect(spyFn).to.have.been.called.with({ name: true });
35+
});
36+
37+
describe('projection operators', () => {
38+
// see more details here https://docs.mongodb.com/v3.2/reference/operator/projection/meta/
39+
it('should pass $meta unflatted', () => {
40+
resolveParams.projection = { score: { $meta: 'textScore' } };
41+
projectionHelper(resolveParams);
42+
expect(spyFn).to.have.been.called.with({ score: { $meta: 'textScore' } });
43+
});
44+
45+
it('should pass $slice unflatted', () => {
46+
resolveParams.projection = { comments: { $slice: 5 } };
47+
projectionHelper(resolveParams);
48+
expect(spyFn).to.have.been.called.with({ comments: { $slice: 5 } });
49+
});
50+
51+
it('should pass $elemMatch unflatted', () => {
52+
resolveParams.projection = { students: { $elemMatch: { school: 102 } } };
53+
projectionHelper(resolveParams);
54+
expect(spyFn).to.have.been.called.with({ students: { $elemMatch: { school: 102 } } });
55+
});
56+
});
2957
});
3058
});

src/resolvers/helpers/projection.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,14 @@ export function projectionHelper(resolveParams: ExtendedResolveParams): void {
88
const projection = resolveParams.projection;
99
if (projection) {
1010
const flatProjection = {};
11-
Object.keys(projection).forEach(key => {
12-
flatProjection[key] = !!projection[key];
11+
Object.keys(projection).forEach((key) => {
12+
if (projection[key].$meta || projection[key].$slice || projection[key].$elemMatch) {
13+
// pass MongoDB projection operators https://docs.mongodb.com/v3.2/reference/operator/projection/meta/
14+
flatProjection[key] = projection[key];
15+
} else {
16+
// if not projection operator, then flatten projection
17+
flatProjection[key] = !!projection[key];
18+
}
1319
});
1420
resolveParams.query = resolveParams.query.select(flatProjection); // eslint-disable-line
1521
}

0 commit comments

Comments
 (0)