Skip to content

Commit 53fa196

Browse files
committed
fix: toMongoDottedObject just dottify internals of logical operators with expressions: $or, $and, $not, $nor. Other operators will have unchanged internals: $in, $near, etc.
closes #201
1 parent fd8f230 commit 53fa196

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

src/utils/__tests__/toMongoDottedObject-test.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,45 @@ describe('toMongoFilterDottedObject()', () => {
8787
});
8888
});
8989

90+
it('should dottify internals of logical operators: $or $and $not $nor', () => {
91+
expect(
92+
toMongoFilterDottedObject({
93+
$and: [{ a: { b: 1 } }, { c: [1, 2] }],
94+
$or: [{ a: { b: 1 } }, { c: [1, 2] }],
95+
some: {
96+
me: {
97+
$nor: [{ a: { b: 1 } }, { c: [1, 2] }],
98+
$not: { a: { b: 1 } },
99+
},
100+
},
101+
})
102+
).toEqual({
103+
$and: [{ 'a.b': 1 }, { 'c.0': 1, 'c.1': 2 }],
104+
$or: [{ 'a.b': 1 }, { 'c.0': 1, 'c.1': 2 }],
105+
'some.me': { $nor: [{ 'a.b': 1 }, { 'c.0': 1, 'c.1': 2 }], $not: { 'a.b': 1 } },
106+
});
107+
});
108+
109+
it('should keep $geometry as is', () => {
110+
expect(
111+
toMongoFilterDottedObject({
112+
location: {
113+
$near: {
114+
$geometry: { type: 'Point', coordinates: [10.3222671, 36.88911649999999] },
115+
$maxDistance: 50000,
116+
},
117+
},
118+
})
119+
).toEqual({
120+
location: {
121+
$near: {
122+
$geometry: { type: 'Point', coordinates: [10.3222671, 36.88911649999999] },
123+
$maxDistance: 50000,
124+
},
125+
},
126+
});
127+
});
128+
90129
it('should handle date object values as scalars', () => {
91130
expect(toMongoFilterDottedObject({ dateField: new Date(100) })).toEqual({
92131
dateField: new Date(100),

src/utils/toMongoDottedObject.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { Types } from 'mongoose';
44
import { isObject } from 'graphql-compose';
55

66
const primitives = [Types.ObjectId, Date, String, Number, Boolean, Types.Decimal128];
7+
const operatorsWithExpression = ['$or', '$and', '$not', '$nor'];
78

89
function isPrimitive(value: any) {
910
return primitives.some(p => value instanceof p);
@@ -17,9 +18,14 @@ function _toMongoDottedObject(obj, target = {}, path = [], filter = false) {
1718
/* eslint-disable */
1819
objKeys.forEach(key => {
1920
if (key.startsWith('$')) {
20-
const val = Array.isArray(obj[key])
21-
? obj[key].map(v => _toMongoDottedObject(v, {}, [], filter))
22-
: _toMongoDottedObject(obj[key], {}, [], filter);
21+
let val;
22+
if (operatorsWithExpression.includes(key)) {
23+
val = Array.isArray(obj[key])
24+
? obj[key].map(v => _toMongoDottedObject(v, {}, [], filter))
25+
: _toMongoDottedObject(obj[key], {}, [], filter);
26+
} else {
27+
val = obj[key];
28+
}
2329
if (path.length === 0) {
2430
target[key] = val;
2531
} else {

0 commit comments

Comments
 (0)