diff --git a/src/parser/serializer.ts b/src/parser/serializer.ts index baf3fe9b..076bd3eb 100644 --- a/src/parser/serializer.ts +++ b/src/parser/serializer.ts @@ -757,7 +757,11 @@ export function serializeInto( // Get the entry values const key = entry.value[0]; - const value = entry.value[1]; + let value = entry.value[1]; + + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } // Check the type of the value const type = typeof value; diff --git a/test/node/to_bson_test.js b/test/node/to_bson_test.js index 1178cda3..0c78ab90 100644 --- a/test/node/to_bson_test.js +++ b/test/node/to_bson_test.js @@ -183,6 +183,15 @@ describe('toBSON', function () { const sizeNestedToBSON = BSON.calculateObjectSize({ a: [0] }); expect(sizeNestedToBSON).to.equal(33); }); + + it('uses toBSON on values contained in a map', () => { + const map = new Map(); + map.set('a', 100); + + const serializedData = BSON.serialize(map); + const deserializedData = BSON.deserialize(serializedData); + expect(deserializedData).to.have.property('a', 'hello number'); + }); }); it('should use toBSON in calculateObjectSize', () => {