Skip to content

Commit a767fa1

Browse files
committed
fix(ext-json): deserialize doubles as Number in relaxed mode
This ensures we take relaxed/strict mode into account when deserializing a double, similar to the integer checks above it. NODE-1639
1 parent 4ba5226 commit a767fa1

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

lib/extended_json.js

+7-5
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,17 @@ const keysToCodecs = {
3838

3939
function deserializeValue(self, key, value, options) {
4040
if (typeof value === 'number') {
41+
if (options.relaxed) {
42+
return value;
43+
}
44+
4145
// if it's an integer, should interpret as smallest BSON integer
4246
// that can represent it exactly. (if out of range, interpret as double.)
4347
if (Math.floor(value) === value) {
44-
let int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,
45-
int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX;
46-
47-
if (int32Range) return options.strict ? new Int32(value) : value;
48-
if (int64Range) return options.strict ? new Long.fromNumber(value) : value;
48+
if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) return new Int32(value);
49+
if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) return new Long.fromNumber(value);
4950
}
51+
5052
// If the number is a non-integer or out of integer range, should interpret as BSON Double.
5153
return new Double(value);
5254
}

test/node/extended_json_tests.js

+6
Original file line numberDiff line numberDiff line change
@@ -247,4 +247,10 @@ describe('Extended JSON', function() {
247247
// timestamp
248248
expect(result.timestamp).to.be.an.instanceOf(BSON.Timestamp);
249249
});
250+
251+
it('should return a native number for a double in relaxed mode', function() {
252+
const result = EJSON.deserialize({ test: 34.12 }, { relaxed: true });
253+
expect(result.test).to.equal(34.12);
254+
expect(result.test).to.be.a('number');
255+
});
250256
});

0 commit comments

Comments
 (0)