Skip to content

Commit 15b6f46

Browse files
committed
fix: toMongoDottedObject() now keep bson ObjectId untouched
1 parent f589fdc commit 15b6f46

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

src/__mocks__/mongooseCommon.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const originalConnect = mongoose.connect;
1212
mongoose.connect = async () => {
1313
const mongoServer = new MongodbMemoryServer();
1414

15-
const mongoUri = await mongoServer.getConnectionString();
15+
const mongoUri = await mongoServer.getConnectionString(true);
1616

1717
originalConnect.bind(mongoose)(mongoUri, { useMongoClient: true });
1818

src/utils/__tests__/toMongoDottedObject-test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/* @flow */
22

3+
import { Types } from 'mongoose';
34
import toMongoDottedObject from '../toMongoDottedObject';
45

56
describe('toMongoDottedObject()', () => {
@@ -40,4 +41,11 @@ describe('toMongoDottedObject()', () => {
4041
'a.dateField': new Date(100),
4142
});
4243
});
44+
45+
it('should keep BSON ObjectId untouched', () => {
46+
const id = new Types.ObjectId();
47+
expect(toMongoDottedObject({ a: { someField: id } })).toEqual({
48+
'a.someField': id,
49+
});
50+
});
4351
});

src/utils/toMongoDottedObject.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
/* @flow */
22

3+
import { Types } from 'mongoose';
4+
5+
const ObjectId = Types.ObjectId;
6+
37
/**
48
* Convert object to dotted-key/value pair
59
* { a: { b: { c: 1 }}} -> { 'a.b.c': 1 }
@@ -24,11 +28,11 @@ export default function toMongoDottedObject(
2428
/* eslint-disable */
2529
objKeys.forEach(key => {
2630
if (key.startsWith('$')) {
27-
target[path.join('.')] = {
31+
target[path.join('.')] = {
2832
...target[path.join('.')],
2933
[key]: obj[key],
3034
};
31-
} else if (Object(obj[key]) === obj[key]) {
35+
} else if (Object(obj[key]) === obj[key] && !(obj[key] instanceof ObjectId)) {
3236
toMongoDottedObject(obj[key], target, path.concat(key));
3337
} else {
3438
target[path.concat(key).join('.')] = obj[key];
@@ -38,7 +42,7 @@ export default function toMongoDottedObject(
3842
if (objKeys.length === 0) {
3943
target[path.join('.')] = obj;
4044
}
41-
45+
4246
return target;
4347
/* eslint-enable */
4448
}

0 commit comments

Comments
 (0)