NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm · #2407 most downloaded on npm
A bson parser for node.js and the browser
Last release 19 days ago
15 Sep 2026
Release timing varies
gaps range from 2 weeks to 5 months
Nearly every release is documented
notes for 53 of 56 stable releases
111 versions withdrawn
withdrawn after publishing
15 years old
185 releases · first in 2011
The MongoDB Node.js team is pleased to announce version 7.3.3 of the bson package!
The MongoDB Node.js team is pleased to announce version 7.3.3 of the bson package!
BSON.calculateObjectSize infinite hangFixed a bug where BSON.calculateObjectSize would hang indefinitely on an object containing a circular reference. The method now throws an exception when a circular reference is detected.
Also a big thank you to @mcmorisi for his contribution on #912 security warning in EJSON.parse documentation!
We invite you to try the bson library immediately, and report any issues to the NODE project.
One column per quarter.
The MongoDB Node.js team is pleased to announce version 7.3.2 of the bson package!
The MongoDB Node.js team is pleased to announce version 7.3.2 of the bson package!
calculateObjectSize() now returns accurate byte counts for Int32 and BSONSymbolPreviously, each Int32 or BSONSymbol value caused a 12-byte overcount.
calculateObjectSize() now yields proper size calculations on ES Map'sThis release of js-bson fixes an issue where we were incorrectly considering ES Map objects inside calculateObjectSize. This issue did not impact serialization, just size calculation.
This release of js-bson fixes an issue where the date boundary for relaxed EJSON was incorrectly set to a date 5 hours after the maximum limit of 10,000 AD.
This release of js-bson fixes an issue where we were making crypto calls during module initialization, which is forbidden by Cloudflare Workers and other environments.
ObjectId now stores its 12 bytes as four inline integers instead of a Uint8Array, cutting per-ObjectId memory by about 63% (and roughly 45 to 47% across large result sets) with no serialization slowdown. Deep equality and cloning are preserved (assert.deepStrictEqual, and lodash isEqual / cloneDeep).
Thanks to @spokodev for contributing their fixes! (NODE-7631 (#901), NODE-7645 (#917), NODE-7646 (#910))
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 7.3.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 7.3.1 of the bson package!
ObjectId initialization now tolerates partial process polyfillsAdds optional chaining to Node.js startup snapshot API calls in ObjectId so that environments with a stubbed or partial process global no longer throw a TypeError at startup.
We invite you to try the bson library immediately, and report any issues to the NODE project.
Deprecated inapplicable Long members on Timestamp
The MongoDB Node.js team is pleased to announce version 7.3.0 of the bson package!
Long members on TimestampTimestamp inherits from Long for storage convenience, but it is semantically a (t, i) pair, not a general 64-bit integer. If you have called Long methods directly on Timestamp instances (for example toNumber(), getHighBits(), getLowBits(), or aithmetic and bitwise operations), those are now marked @deprecated with no runtime behavior changes. The .t and .i accessors provide direct, semantically consistent access to the two timestamp components.
BSON operations no longer throw on deeply nested documentsCore serialization and deserialization function (serialize, deserialize, calculateObjectSize) have been rewritten as iterative algorithms, so a sufficiently-nested document will no longer exhaust the call stack.
As a side effect of the rewrite, a Code with Scope scope that happens to carry $ref, $id, and $db keys is no longer promoted to a DBRef instance. The scope is returned as a plain object, which is the correct behavior: a scope represents JavaScript variable bindings, not a document reference.
new Binary(buffer, subType) now coerces subType to match BSON bytesThe Binary constructor now normalizes subtype inputs to match BSON serialization. Previously, passing a stringified subtype like '4' would cause a mismatch between the sub_type property (string '4') and the serialized BSON value (0x04). The constructor now converts inputs to ensure consistency.
EJSON.stringify now correctly handles all parameter combinationsPreviously, calling EJSON.stringify(value, options, space) silently discarded the space parameter, producing unformatted output. This has been fixed so all documented call signatures work as expected:
// This now correctly produces indented canonical EJSON
EJSON.stringify(doc, { relaxed: false }, 2);Thanks to @chdanielmueller for working on this problem!
ObjectId now resets its random state (process-unique bytes and counter seed) when a process restores from a Node.js startup snapshot. Previously these values were frozen into the snapshot blob, causing processes restored from the same snapshot to generate colliding ObjectIds.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 7.2.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 7.2.0 of the bson package!
EJSON now supports ignoreUndefinedserialize supports an option, ignoreUndefined, which instructs the serializer to skip any keys whose values are undefined.
This option has been added to EJSON:
> EJSON.stringify({ a: undefined }, { ignoreUndefined: true });
'{}'
> EJSON.stringify({ a: undefined }, { ignoreUndefined: false });
'{"a":null}'
> EJSON.serialize({ a: undefined }, { ignoreUndefined: true });
{}
> EJSON.serialize({ a: undefined }, { ignoreUndefined: false });
{ a: null }This option defaults to false.
Buffer.copy() now present in ByteUtilsByteUtils now contains a copy() method, we behaves identically to Nodejs' Buffer.copy() method.
We invite you to try the bson library immediately, and report any issues to the NODE project.
Fix breaking change to onDemand namespace
The MongoDB Node.js team is pleased to announce version 7.1.1 of the bson package!
onDemand namespaceThis fix reverts the breaking change made as part of NODE-7334 and restores compatibility with v7.0.0 of the MongoDB Node.js Driver.
We invite you to try the bson library immediately, and report any issues to the NODE project.
Caution This release contains an inadvertent breaking change and has been deprecated on npm.
Caution
This release contains an inadvertent breaking change and has been deprecated on npm.
The MongoDB Node.js team is pleased to announce version 7.1.0 of the bson package!
ByteUtils added as a binary utillityByteUtils are now public and provide set of platform-agnostic tools to manipulate binary data (using Buffer in nodejs-compatible environments and fallback to Uint8Array).
Note
This feature is experimental and may change at any time
NumberUtils is now exported in the libraryBSON maintains a set of utilities for reading to and from buffers of bytes. This module is now exported from the BSON package.
import { NumberUtils } from 'bson';Note
NumberUtils is experimental and may change at any time.
ByteUtils and NumberUtils removed from onDemand namespaceThe experimental ByteUtils and NumberUtils helpers have been moved from the onDemand namespace to the top-level package export.
onDemand ns (#859) (92bbc34)We invite you to try the bson library immediately, and report any issues to the NODE project.
BSON Binary subtype 2 constant deprecated
The MongoDB Node.js team is pleased to announce version 7.0.0 of the bson package!
The minimum supported Node.js version is now v20.19.0. We strive to keep our minimum supported Node.js version in sync with the runtime's release cadence to keep up with the latest security updates and modern language features. Our TypeScript target has also been updated to ES2023.
BSON now uses Javascript BigInt syntax and requires a JS engine with support for BigInt literal syntax.
globalThis.crypto for random byte generationUntil BSON@7.x, BSON has supported Node.js v16. Node.js v16 does not include crypto in the global object, which necessitated importing crypto from node:crypto. This require has caused many headaches for bundlers. We improved the situation in NODE-6074, but this release updates our Node.js bundle to rely on the global object instead and removes all requires from the bundle.
atob, btoa, and TextEncoder for react native buildsThe React Native JS engine (Hermes) now supports atob, btoa, and TextEncoder natively and polyfills are no longer needed. BSON no longer includes these polyfills for react native builds.
If you wish to create an ObjectId from a numeric timestamp, use ObjectId.createFromTime() instead.
BSON Binary subtype 2 was previously deprecated in the BSON specification, but the corresponding subtype constant remained available in the BSON library. This constant has now been deprecated to align with the specification.
bsonType symbol property as an alias for _bsontypeJS classes representing BSON values now have a bsonType symbol property as an alias for the existing _bsontype property. This makes it easier to distinguish between values of a specific BSON type and documents with arbitrary keys after deserializing:
import { bsonType, deserialize } from 'bson';
const doc = deserialize(...);
// will be set when doc.value is a BSON wrapper class **or** a sub-document { _bsontype: '...' }
console.log(doc.value._bsontype);
// will be set if and only if doc.value is a BSON wrapper class
console.log(doc.value[bsonType]);It is safe to replace all uses of value._bsontype with value[bsonType].
_bsontype (#829) (1e1b619)We invite you to try the bson library immediately, and report any issues to the NODE project.
NODE-7271 : revert private property usage in ObjectId
7.0.0-alpha.1 (2025-10-21) ⚠ BREAKING CHANGES bump BSON_MAJOR_VERSION to 7 ( #832 ) Features bump BSON_MAJOR_VERSION to 7
NODE-7099 : deprecate BSON binary subtype 2 constant
_bsontype (#829) (1e1b619)The MongoDB Node.js team is pleased to announce version 6.10.4 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.10.4 of the bson package!
In versions <6.10.4, BSON uses a top-level await to asynchronously import the crypto module. This change unintentionally caused headaches for users of webpack, react native, vite and other tools bundlers and tools.
The top-level await has been removed from all BSON bundles. Thanks to @lourd for this contribution.
This adds validation to our BSON.serialize and EJSON.stringify methods that will prevent creating float 32 vectors that are not a multiple of 4. Previously created vectors that do not meet this validation will still be deserialized and parsed so they can be fixed.
Additionally, the toFloat32Array(), toInt8Array(), and toPackedBits() methods now perform the same validation that serialize does to prevent use of incorrectly formatted Binary vector values. (For example, a packed bits vector with more than 7 bits of padding)
Vectors of an incorrect length could only be made manually (directly constructing the bytes and calling new Binary). We recommend using toFloat32Array and fromFloat32Array when interacting with Vectors in MongoDB as they handle the proper creation and translation of this data type.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.10.3 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.10.3 of the bson package!
useBigInt64 is enabledAfter refactoring to improve deserialization performance in #649, we inadvertently introduced a bug that manifested when deserializing Long values with the useBigInt64 flag enabled. The bug would lead to negative Long values being deserialized as unsigned integers. This issue has been resolved here.
Thanks to @rkistner for reporting this bug!
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.10.2 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.10.2 of the bson package!
calculateObjectSize not accounting for BigInt value sizeBSON.calculateObjectSize was missing a condition for BigInt values, meaning it did not account for them in the same way that it would for Long values. This has been corrected so that Bigint values contribute 8 bytes worth of size to the total count.
We also added a new default condition that will catch any new values that may be returned by typeof in the future and will throw an error rather than returning an inaccurate size.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.10.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.10.1 of the bson package!
As an optimization, a previous performance improvement stored the type information of seen objects to avoid recalculating type information. This caused an issue in the driver under extreme load and high memory usage as the cache grew. The assumption was that garbage collection would clear it enough to sustain normal operation. The cache is now removed and other optimal type checking is used in its place.
When ObjectId.cacheHexString is set to true we no longer convert the buffer to a hex string in the constructor, since the cache is already being filled in any call to objectid.toHexString().
Additionally, if a string is passed into the constructor we can cache this immediately as there is no performance impact and no extra memory that needs to be allocated.
This improves the performance for situations where you are parsing ObjectIds from a string (ex. JSON) and want to avoid recalculating the hex. It also improves situations where you have ObjectIds coming from BSON and only convert some of them strings perhaps after applying some filter to eliminate some.
With cacheHexString enabled deserializing ObjectIds from BSON shows ~80% performance improvement and toString-ing ObjectIds that were constructed from a string convert ~40% faster!
Thanks to @SeanReece for contributing this improvement!
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.10.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.10.0 of the bson package!
The Binary class has new helpers to assist with using the newly minted Vector sub_type of Binary sub_type == 9 :tada:! For more on how these types can be used with MongoDB take a look at How to Ingest Quantized Vectors!
Here's a summary of the API:
class Binary {
toInt8Array(): Int8Array;
toFloat32Array(): Float32Array;
toPackedBits(): Uint8Array;
static fromInt8Array(array: Int8Array): Binary;
static fromFloat32Array(array: Float32Array): Binary;
static fromPackedBits(array: Uint8Array, padding: number = 0): Binary;
}
Relatively self-explanatory: each one supports converting to and constructing from a native Javascript data type that corresponds to one of the three vector types: Int8, Float32, PackedBit.
When a Binary is sub_type 9 the first two bytes are set to important metadata about the vector.
binary.buffer[0] - The datatype that indicates what the following bytes are.binary.buffer[1] - The padding amount, a value 0-7 that indicates how many bits to ignore in a PackedBit vector.static fromPackedBits(array: Uint8Array, padding: number = 0)When handling packed bits, the last byte may not be entirely used. For example, a PackedBit vector = [0xFF, 0xF0] with padding = 4 ignores those last four 0s making the bit vector logically equal to 12 ones.
F F F 0
[1111 1111 1111] // ignored: the four 0s are padding
[!IMPORTANT] When using the
fromPackedBitsmethod to set your padding amount to avoid inadvertently extending your bit vector.
Packed bits get special treatment with two styles of conversion methods to suit your vector-y needs. toBits will return individually addressable bits shifted apart into an array. fromBits takes the same format in reverse and packs the bits into bytes.
Notice there is no argument to set the padding. That is because it can be determined by the array's length. Recall those 12 ones from the previous example, well, the padding has to be 4 to reach a multiple of 8.
class Binary {
toBits(): Int8Array;
static fromBits(bits: ArrayLike<number>): Binary;
}
[!CAUTION] We highly encourage using ONLY these methods to interact with vector data and avoid operating directly on the byte format. Other Binary class methods (
put(),write()read(), andvalue()) and direct access of data in a Binary'sbufferbeyond the 1st index should only be used in exceptional circumstances and with extreme caution after closely consulting the BSON Vector specification.Details to keep in mind
- A javascript engine's endianness is platform dependent whereas BSON is always in little-endian format so if viewing bytes as Float32s take care to re-order bytes as needed.
- Int8 vectors are signed bytes but
read()always returns unsigned bytes.- The vector data begins at offset
2.
read() returns a view of Binary.bufferBinary's read() return type claimed it would return number[] or Uint8Array which was true in previous BSON versions that didn't always store a Uint8Array on the buffer property like Binary does today.
read()'s length parameter did not respect the position value allowing reading bytes beyond the data that is actually stored in the Binary. This has been corrected.
Additionally, this method returned a view in Node.js environments and a copy in Web environments. it has been fixed to always return a view.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.9.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.9.1 of the bson package!
useBigInt64 is enabledAfter refactoring to improve deserialization performance in #649, we inadvertently introduced a bug that manifested when deserializing Long values with the useBigInt64 flag enabled. The bug would lead to negative Long values being deserialized as unsigned integers. This issue has been resolved here.
Thanks to @rkistner for reporting this bug!
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.9.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.9.0 of the bson package!
t and i propertiesTo make this type a bit easier to use we are surfacing the breakdown of the two internal 32 bit segments of a Timestamp value.
const ts = new Timestamp({ i: 2, t: 1 });
ts.i // 2
ts.t // 1
ObjectId.isValid(string) performance improvementOften used to validate whether a hex string is the correct length and proper format before constructing an ObjectId for querying, the isValid function will validate strings much faster than before. Many thanks to @SeanReece for the contribution!
Optimizations have been implemented with respect to BSON serialization across the board, resulting in up to 20% gains in serialization with a sample of MFlix documents. Thanks again to @SeanReece for the contribution!
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.8.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.8.1 of the bson package!
useBigInt64 is enabledAfter refactoring to improve deserialization performance in #649, we inadvertently introduced a bug that manifested when deserializing Long values with the useBigInt64 flag enabled. The bug would lead to negative Long values being deserialized as unsigned integers. This issue has been resolved here.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.8.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.8.0 of the bson package!
The Github release for js-bson now contains a detached signature file for the NPM package (named
bson-X.Y.Z.tgz.sig), on every major and patch release to 6.x and 5.x. To verify the signature, follow the instructions in the 'Release Integrity' section of the README.md file.
Long.fromBigIntInternally fromBigInt was originally implemented using toString of the bigint value. Now, Long.fromBigInt has been refactored to use bitwise operations greatly improving performance.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.7.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.7.1 of the bson package!
useBigInt64 is enabledAfter refactoring to improve deserialization performance in #649, we inadvertently introduced a bug that manifested when deserializing Long values with the useBigInt64 flag enabled. The bug would lead to negative Long values being deserialized as unsigned integers. This issue has been resolved here.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.7.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.7.0 of the bson package!
Long.fromStringStrict methodThe Long.fromStringStrict method is almost identical to the Long.fromString method, except it throws a BSONError if any of the following are true:
Unlike Long.fromString, this method does not coerce the inputs '+/-Infinity' and 'NaN' to Long.ZERO, in any case.
Examples:
Long.fromStringStrict('1234xxx5'); // throws BSONError
Long.fromString('1234xxx5'); // coerces input and returns new Long(123400)
// when writing in radix 10, 'n' and 'a' are both invalid characters
Long.fromStringStrict('NaN'); // throws BSONError
Long.fromString('NaN'); // coerces input and returns Long.ZERO
[!NOTE]
Long.fromStringStrict's functionality will be present inLong.fromStringin the V7 BSON release.
Double.fromString methodThis method attempts to create an Double type from a string, and will throw a BSONError on any string input that is not representable as a IEEE-754 64-bit double.
Notably, this method will also throw on the following string formats:
'Infinity', '-Infinity', and 'NaN' input strings are still allowed)Int32.fromString methodThis method attempts to create an Int32 type from string, and will throw a BSONError on any string input that is not representable as an Int32.
Notably, this method will also throw on the following string formats:
Strings with leading zeros, however, are allowed
BSONError on overlong encodings in Node.jsSpecifically, this affects deserialize when utf8 validation is enabled, which is the default.
An overlong encoding is when the number of bytes in an encoding is inflated by padding the code point with leading 0s (see here for more information).
Long.fromString takes radix into account before coercing '+/-Infinity' and 'NaN' to Long.ZEROLong.fromString no longer coerces the following cases to Long.ZERO when the provided radix supports all characters in the string:
'+Infinity', '-Infinity', or 'Infinity' when 35 <= radix <= 36'NaN' when 24 <= radix <= 36// when writing in radix 27, 'n' and 'a' are valid characters, so 'NaN' represents the decimal number 17060
Long.fromString('NaN', 27); // new Long(17060)
Long.fromString('NaN', 10); // new Long(0) <-- Since 'NaN' is not a valid input in base 10, it gets coerced to Long.ZERO
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.6.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.6.1 of the bson package!
useBigInt64 is enabledAfter refactoring to improve deserialization performance in #649, we inadvertently introduced a bug that manifested when deserializing Long values with the useBigInt64 flag enabled. The bug would lead to negative Long values being deserialized as unsigned integers. This issue has been resolved here.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.6.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.6.0 of the bson package!
Binary.toString and Binary.toJSON align with BSON serializationWhen BSON serializes a Binary instance it uses the bytes between 0 and binary.position since Binary supports pre-allocating empty space and writing segments of data using .put()/.write(). Erroneously, the toString() and toJSON() methods did not use the position property to limit how much of the underlying buffer to transform into the final value, potentially returning more string than relates to the actual data of the Binary instance.
In general, you may not encounter this bug if Binary instances are created from a data source (new Binary(someBuffer)) or are returned by the database because in both of these cases binary.position is equal to the length of the underlying buffer.
Fixed example creating an empty Binary:
new BSON.Binary().toString();
// old output: '\x00\x00\x00\x00...' (256 zeros)
// new output: ''
This release contains experimental APIs that are not suitable for production use. As a reminder, anything marked @experimental is not a part of the stable semantically versioned API and is subject to change in any subsequent release.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.5.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.5.1 of the bson package!
useBigInt64 is enabledAfter refactoring to improve deserialization performance in #649, we inadvertently introduced a bug that manifested when deserializing Long values with the useBigInt64 flag enabled. The bug would lead to negative Long values being deserialized as unsigned integers. This issue has been resolved here.
Thanks to @rkistner for reporting this bug!
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.5.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.5.0 of the bson package!
[!CAUTION] Among the platforms BSON and the MongoDB driver support this issue impacts s390x big-endian systems. x86, ARM, and other little-endian systems are not affected. Existing versions of the driver can be upgraded to this release.
A recent change to the BSON library started parsing and serializing floats using a Float64Array. When reading the bytes from this array the ordering is dependent on the platform it is running on and we now properly account for that ordering.
SUBTYPE_SENSITIVE on Binary classWhen a BSON.Binary object is of 'sensitive' subtype, the object's subtype will equal 0x08.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.4.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.4.1 of the bson package!
useBigInt64 is enabledAfter refactoring to improve deserialization performance in #649, we inadvertently introduced a bug that manifested when deserializing Long values with the useBigInt64 flag enabled. The bug would lead to negative Long values being deserialized as unsigned integers. This issue has been resolved here.
[!CAUTION] Among the platforms BSON and the MongoDB driver support this issue impacts s390x big-endian systems. x86, ARM, and other little-endian systems are not affected. Existing versions of the driver can be upgraded to this release.
A change in BSON@6.4.0 (2024-02-29) started parsing and serializing floats using a Float64Array. When reading the bytes from this array the ordering is dependent on the platform it is running on and we now properly account for that ordering.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.4.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.4.0 of the bson package!
The BSON library's string encoding logic now attempts to optimize for basic latin (ASCII) characters. This will apply to both BSON keys and BSON values that are or contain strings. If strings are less than 6 bytes we observed approximately 100% increase in speed while around 24 bytes the performance was about 33% better. For any non-basic latin bytes or at 25 bytes or greater the BSON library will continue to use Node.js' Buffer.toString API.
The intent is to generally target the serialization of BSON keys which are often short and only use basic latin.
We do recommend that users of the driver use the BSON APIs exported from the driver. One reason for this is at this time the driver is only shipped in commonjs format and as a result it will only import the commonjs BSON bundle. If in your application you use import syntax then there will be a commonjs and an es module instance in the current process which prevents things like instanceof from working.
Also, private symbols defined in one package will not be equal to symbols defined in the other. This caused an issue on ObjectId's private symbol property preventing the .equals method from one package from operating on an ObjectId created from another.
Thanks to @dot-i's contribution we've changed the private symbol to a private string property so that the .equals() method works across module types.
If BSON data does not contain Doubles and UTF8 validation is disabled the deserializer is careful to not allocate data structures needed to support that functionality. This has shown to greatly increase (2x-1.3x) the performance of the deserializer.
Thank you @billouboq for this contribution!
When serializing ObjectIds, Decimal128, and UUID values we can get better performance by writing the byte-copying logic in Javascript for loops rather than using the TypedArray.set API. ObjectId serialization performance is 1.5x-2x faster.
We now use bit shifting and multiplication operators in place of DataView getX/setX calls to parse and serialize bigints and a Float64Array to convert a double to bytes. This change has been shown to increase deserializing performance ~1.3x and serializing performance ~1.75x.
For small allocations Node.js performance can be improved by using pre-allocated pooled memory. ObjectIds and Decimal128 instance will now use allocUnsafe on Node.js.
We invite you to try the bson library immediately, and report any issues to the NODE project.
NODE-3034: deprecate number as an input to ObjectId constructor
The MongoDB Node.js team is pleased to announce version 6.3.0 of the bson package!
The BSON library's string decoding logic now attempts to optimize for basic latin (ASCII) characters. This will apply to both BSON keys and BSON values that are or contain strings. If strings are less than 6 bytes we observed approximately ~100% increase in speed while around 15 bytes the performance was about ~30% better. For any non-basic latin bytes or at 20 bytes or greater the BSON library will continue to use Node.js' Buffer.toString API.
The intent is to generally target the deserialization of BSON keys which are often short and only use basic latin, <i>Et tu, _id?</i>
number type as input to the ObjectId constructor is deprecatedInstead, use static createFromTime() to set a numeric value for the new ObjectId.
// previously
new ObjectId(Date.now())
// recommended
ObjectId.createFromTime(Date.now())
ObjectId constructor (#640) (44bec19)We invite you to try the bson library immediately, and report any issues to the NODE project.
Our intention is to prevent cross-major BSON types from reaching the serialization logic as breaking changes to the types could lead to silent incompa…
The MongoDB Node.js team is pleased to announce version 6.2.0 of the bson package!
<img width="1064" alt="Post Color BSON Objects" src="https://github.com/mongodb/js-bson/assets/106987683/0076238f-dabf-4dbc-87d1-cd56c3efb711">
Previously, our thrown BSONVersionError stated that the "bson type must be from 6.0 or later". Our intention is to prevent cross-major BSON types from reaching the serialization logic as breaking changes to the types could lead to silent incompatibilities in the serialization process. We've updated the message to make that intention clear: "bson types must be from bson 6.x.x".
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 6.1.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 6.1.0 of the bson package!
Decimal128.fromStringWithRounding static methodFollowing the merging of the Decimal128.fromString bug fix in #613, we understand that some users may have been relying on our inexact rounding behaviour in their applications. To address this need, we have exposed the inexact rounding behaviour via a new static method, Decimal128.fromStringWithRounding.
Thank you to @hconn-riparian for reporting a related rounding bug and fix in #560 which has been included in this feature.
// 5.x
> let d = Decimal128.fromString('127341286781293491234791234667890123')
new Decimal128("1.273412867812934912347912346678901E+35")
// 6.x
> let d = Decimal128.fromString('127341286781293491234791234667890123')
Uncaught:
BSONError: "127341286781293491234791234667890123" is not a valid Decimal128 string - inexact rounding
at invalidErr (./js-bson/lib/bson.cjs:1402:11)
at Decimal128.fromStringInternal (./js-bson/lib/bson.cjs:1633:25)
at Decimal128.fromString (./js-bson/lib/bson.cjs:1424:27)
> d = Decimal128.fromStringWithRounding('127341286781293491234791234667890123')
new Decimal128("1.273412867812934912347912346678901E+35")
See our driver specifications for more information on inexact rounding.
ObjectId serialization performanceThanks to @billouboq for submitting the performance fix merged in #614. When using a for-loop instead of creating a new 12 byte view before calling Uint8Array.prototype.set, our internal testing shows a 25% increase in MB/s throughput of ObjectId serialization!
We invite you to try the bson library immediately, and report any issues to the NODE project.
…byte sequence, so we are considering this a breaking change and removing it in this major release.
The MongoDB Node.js team is pleased to announce version 6.0.0 of the bson package!
In this major version update, we focused on removing deprecated or otherwise difficult to use APIs and fixing impactful bugs.
[!Important] The
BSON_MAJOR_VERSIONhas been bumped to 6. Only BSON objects that have this major version can be serialized with this version of the library. Mismatched objects will throw aBSONVersionErrorwhen attempting to serialize.
[!Important] The minimum supported Node.js version is now v16.20.1. We strive to keep our minimum supported Node.js version in sync with the runtime's release cadence to keep up with the latest security updates and modern language features.
Decimal128 constructor now throws when detecting loss of precisionPrior to this release, Decimal128 would round numbers with more than 34 significant digits and lose precision. Now, on detecting loss of precision, Decimal128's constructor and Decimal128.fromString will throw a BSONError. This behaviour should have been the default as the Decimal128 class was always intended to be high-precision floating point value. As such, silently rounding is undesirable behaviour as it can potentially result in data loss.
// previous behaviour
> new Decimal128('10000000000000000000000000000000001')
new Decimal128("1.000000000000000000000000000000000E+34")
// new behaviour
> new Decimal128('10000000000000000000000000000000001')
Uncaught:
BSONError: "10000000000000000000000000000000001" is not a valid Decimal128 string - inexact rounding
at invalidErr (bson/lib/bson.cjs:1402:11)
at Decimal128.fromString (bson/lib/bson.cjs:1555:21)
at new Decimal128 (bson/lib/bson.cjs:1411:37)
Note a separate method with corrected rounding behaviour will be available in the next minor version of this library. Additionally a fix for this bug and the aforementioned new method with corrected rounding will be added in the next minor release of v5 of this library.
(From String.length): [The String length] property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by length to not match the actual number of Unicode characters in the string.
The ObjectId constructor erroneously interpreted a string with length of 12 as UTF8 bytes that could be converted to an ObjectId. This is unexpected for at least two reasons. The first is that a legacy approach (pre- Uint8Arrays) to handling binary data was to pass around "binary strings", where each character represents a single byte, this is not the same as interpreting a sting as UTF8, which has restrictions on how each byte can be formatted. The second is that a string of length 12 does not result in 12 bytes of data when converted to utf8 (ex. '🐶🐶🐶🐶🐶🐶'.length === 12, but as UTF8 bytes this is a 24-byte sequence).
Despite the bugginess of the behavior discussed above, the right string in the right context does create the proper byte sequence, so we are considering this a breaking change and removing it in this major release.
Binary (a.k.a 'latin1', 'binary')The Binary BSON type no longer accepts a string as a constructor argument nor can write() be invoked with a string argument. Both methods interpreted strings as binary sequences rather than UTF-8 or base64 which are much more common and expected formats. If there is a string representation of your data it is now expected that the logic that interprets the string format exists outside the Binary class to avoid misinterpreting data. Additionally, .value() only returns a Uint8Array/Buffer that is properly sized to the data. Internally Binary may maintain a .buffer property larger than the the actual data that will be written to BSON bytes. Use .value() to obtain only the bytes relevant to your Binary data.
new Binary(Buffer.from('ÿÿ', 'binary'));
// Binary.createFromBase64("//8=", 0)
new Binary(Buffer.from('ÿÿ', 'utf8'));
// Binary.createFromBase64("w7/Dvw==", 0)
new Binary(Buffer.from('AAAA', 'base64'))
// Binary.createFromBase64("AAAA", 0)
ObjectId.equals now accepts undefined and null parametersThanks to @vanstinator for providing this pull request fixing our ObjectId.equals signature to properly allow checking equality with nullish values.
> const oid = new ObjectId()
// Old behaviour
> oid.equals(undefined) // error TS2345: Argument of type 'undefined' is not assignable to parameter of type 'string | ObjectId | ObjectIdLike'.
// New Behaviour
> oid.equals(undefined)
false
UUID.cacheHexString propertyThis property was unused and so was removed.
We invite you to try the bson library immediately, and report any issues to the NODE project.
Nothing published for this version
NODE-5223: remove deprecated cacheHexString
Nothing published for this version
Our intention is to prevent cross-major BSON types from reaching the serialization logic as breaking changes to the types could lead to silent incompa…
The MongoDB Node.js team is pleased to announce version 5.5.1 of the bson package!
Previously, our thrown BSONVersionError stated that the "bson type must be from 6.0 or later". Our intention is to prevent cross-major BSON types from reaching the serialization logic as breaking changes to the types could lead to silent incompatibilities in the serialization process. We've updated the message to make that intention clear: "bson types must be from bson 6.x.x".
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.5.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 5.5.0 of the bson package!
This release is focused on a bug fix and a new feature for our Decimal128 class.
Decimal128 constructor and Decimal128.fromString now throw when detecting loss of precisionPrior to this release, Decimal128 would round numbers with more than 34 significant digits and lose precision. Now, on detecting loss of precision, Decimal128's constructor and Decimal128.fromString will throw a BSONError. This behaviour should have been the default as the Decimal128 class was always intended to be high-precision floating point value. As such, silently performing inexact rounding is undesirable behaviour.
Decimal128.fromStringWithRounding static methodWe understand that some of our users may have depended on the rounding behaviour of Decimal128.fromString for their applications. To support these users, we have exposed this behaviour via the Decimal128.fromStringWithRounding method. Anywhere that Decimal128.fromString was used with the expectation that rounding would occur can be replaced with a call to this new method.
We also want to express our gratitude to @hconn-riparian for reporting a related rounding bug and fix in #560 which has been included in our implementation of this feature.
// pre v5.5
> let d = Decimal128.fromString('127341286781293491234791234667890123')
new Decimal128("1.273412867812934912347912346678901E+35")
// >= v5.5
> let d = Decimal128.fromString('127341286781293491234791234667890123')
Uncaught:
BSONError: "127341286781293491234791234667890123" is not a valid Decimal128 string - inexact rounding
at invalidErr (./js-bson/lib/bson.cjs:1402:11)
at Decimal128.fromStringInternal (./js-bson/lib/bson.cjs:1633:25)
at Decimal128.fromString (./js-bson/lib/bson.cjs:1424:27)
> d = Decimal128.fromStringWithRounding('127341286781293491234791234667890123')
new Decimal128("1.273412867812934912347912346678901E+35")
Read more about inexact rounding and the rationale for this change in our Decimal128 specification.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.4.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 5.4.0 of the bson package!
The BSON package now ships a bundle made to work on React Native without additional polyfills preconfigured. The necessary APIs (TextEncoder/TextDecoder & atob/btoa) are now vendored into the RN bundle directly. Users should still install react-native-get-random-values themselves to get securely generated UUIDs and ObjectIds. Read more in the React Native section of our readme.
In the v5 major release of BSON we internally abstracted the different byte manipulation APIs used based on whether the library is running in Node.js or in a browser. This abstraction required us to create a subarray before invoking the environment's UTF8 decoding API. Creating the subarray before invoking Node.js' Buffer.prototype.toString API turns out to cause an unnecessary slow down. We have now updated the UTF8 stringification step on Node.js to invoke Buffer.prototype.toString with the start and end offsets. See #585 for our research.
We invite you to try the bson library immediately, and report any issues to the NODE project.
NODE-5224: deprecate UUID hex string cache control
The MongoDB Node.js team is pleased to announce version 5.3.0 of the bson package!
This release fixes a strictness issue with our UUID class. The UUID class has and will continue to generate UUID v4 bytes. However, now when reading UUIDs from MongoDB the UUID can be whatever format was inserted to the database, instead of throwing an error. This will notably help with data that has empty GUID values.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.2.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 5.2.0 of the bson package!
With this release we've added APIs to create BSON Binary / UUID / ObjectId types from hex and base64 strings.
class ObjectId {
static createFromHexString(hex: string): ObjectId;
static createFromBase64(base64: string): ObjectId;
}
class Binary {
static createFromHexString(hex: string, subType? number): Binary;
static createFromBase64(base64: string, subType? number): Binary;
}
class UUID extends Binary {
static override createFromHexString(hex: string): UUID;
static override createFromBase64(base64: string): UUID;
}
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.1.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 5.1.0 of the bson package!
EJSON.stringify now supports ES Map!
import { EJSON } from 'bson';
const m = new Map([
['a', new Map([['b', 1]])],
['b', 2]
]);
console.log(EJSON.stringify(m))
// '{"a":{"b":1},"b":2}'
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 5.0.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 5.0.1 of the bson package!
We invite you to try the bson library immediately, and report any issues to the NODE project.
NODE-4704: remove deprecated ObjectId methods
The MongoDB Node.js team is pleased to announce version 5.0.0 of the bson package!
BSON v5 is out and ready to rumble!
The focus of this release was to modernize our library's approach to delivering a unified cross-platform JavaScript experience.
We no longer support EOL Node.js versions, so the new minimum requirement for the library is v14.20.1 or later.
With ES modules no longer experimental and top-level await available, BSON now offers a native ESM bundle that works in Node.js and the browser in addition to the existing CommonJS format.
Our main improvement centers around the code's use of Uint8Array on the web and Buffer in Node.js.
By pulling out all the byte-by-byte helpers needed to parse and create BSON documents we were able to accomplish the original vision of the Node.js project: true isomorphism (almost!). Our ES module build of the library is runnable in Node.js and the browser, without shims or polyfills. We are so excited for this "write once, run everywhere" future!
The Remove reliance on Node.js Buffer section in the migration guide provides more detail.
Speaking of modernization, we are delighted to announce support for BigInt as a native way to represent and interact with BSON int64s!
JavaScript introduced an infinite precision integer type called BigInt in 2018. BSON 5.0 supports Nodejs 14+, which enables us to use it as an alternate numeric representation for BSON Longs. You can start sending BigInts down into BSON right away: BSON.serialize and EJSON.stringify understand how to convert them into BSON Long and EJSON's $numberLong format.
Returning BigInts is not enabled by default, however this can be accomplished by adding the useBigInt64: true flag in BSON.deserialize or EJSON.parse. For more information on how we transform BigInt’s to 64-bit Integers see the abstract ToBigInt64 operation.
Note: Full support for this feature is not going to be available in the driver v5.0.0 release, we are intending to make it available in the first feature release after 5.0.0
We have a detailed migration guide that provides more context on the changes listed below.
We hope you love BSON as much as we do. :green_heart: :technologist:
We invite you to try the bson library and report any issues to the NODE project.
This alpha build is intended for internal testing only. Adopt at your own risk.
This alpha build is intended for internal testing only. Adopt at your own risk.
Changes listed in HISTORY.md.
5.0.0-alpha.2 diff v5.0.0-alpha.3 (2023-01-20)
This alpha build is intended for internal testing only. Adopt at your own risk.
This alpha build is intended for internal testing only. Adopt at your own risk.
Changes listed in HISTORY.md.
5.0.0-alpha.1 diff v5.0.0-alpha.2 (2023-01-10)
This alpha build is intended for internal testing only. Adopt at your own risk.
This alpha build is intended for internal testing only. Adopt at your own risk.
Changes listed in HISTORY.md.
5.0.0-alpha.0 diff v5.0.0-alpha.1 (2022-12-19)
This alpha build is intended for internal testing only. Adopt at your own risk.
This alpha build is intended for internal testing only. Adopt at your own risk.
Changes listed in HISTORY.md.
5.0.0-alpha.0 diff 4.7.0 (2022-12-16)
The MongoDB Node.js team is pleased to announce version v4.7.2 of the bson package!
The MongoDB Node.js team is pleased to announce version v4.7.2 of the bson package!
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version v4.7.1 of the bson package!
The MongoDB Node.js team is pleased to announce version v4.7.1 of the bson package!
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.7.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.7.0 of the bson package!
This release adds automatic UUID support. Now when serializing or deserializing BSON you can work directly with the UUID type without explicit conversion methods. The UUID class is now a subclass of binary so all existing code will continue to work (including the explicit conversion methods .toUUID/.toBinary). The same automatic support for UUID is also present in EJSON .parse/.stringify.
Take a look at the following for the expected behavior:
const document = BSON.deserialize(bytes)
// { uuid: UUID('xxx') }
BSON.serialize(document)
// Buffer < document with uuid (binary subtype 4) >
Special thanks to @aditi-khare-mongoDB for all her hard work on this feature!! 🎉
We invite you to try the bson library immediately, and report any issues to the NODE project.
__proto__ well in EJSON (#506) (4bda57d)The MongoDB Node.js team is pleased to announce version 4.6.5 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.6.5 of the bson package!
Along with some other bug fixes listed below in this release we've fixed the float parser logic for both deserialize and serialize to use JS Dataview APIs. The most delightful part of this change is an improvement to performance of serializing 64-bit floats. :tada: 🐎
- cpu: Apple M1
- cores: 8
- os: darwin
- ram: 16GB
- iterations: 1,000,000
testing: Double Serialization
current - v 4.6.5 - avg 0.00024913ms
previous release - v 4.6.4 - avg 0.00036335ms
previous major - v 1.1.6 - avg 0.00036459ms
__proto__ well in EJSON (#506) (4bda57d)We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.6.4 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.6.4 of the bson package!
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.6.3 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.6.3 of the bson package!
This release improves documentation for BSON type classes by adding an @category tag to the doc comments.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.6.2 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.6.2 of the bson package!
This release includes a few fixes to the ObjectId class, including performance improvements in ObjectId.equals.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.6.1 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.6.1 of the bson package!
This release includes a few fixes to the validation checks in some of our constructors.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.6.0 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.6.0 of the bson package!
This release adds a new BSON validation option that allows top-level keys to have utf-8 validation disabled or enabled, either on a global or key-specific scale, rather than defaulting to automatic utf-8 validation across all keys. Additionally, it includes a bug fix which allows BSONError and BSONTypeError to be checked with instanceof checks.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.5.4 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.5.4 of the bson package!
This release notably includes a fix to the ObjectId constructor ensuring correct handling of invalid input.
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.5.3 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.5.3 of the bson package!
This release includes a few minor changes for spec compliance, primarily around validation, as detailed below:
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.5.2 of the bson package!
The MongoDB Node.js team is pleased to announce version 4.5.2 of the bson package!
Some APIs were marked internal that should've been public. We've also add toString methods to our Int32 and Double classes that wrap Javascript's Number.toString() method.
Additionally a bug in Decimal128 was corrected where the representation string was wrongly used to find the significant digits. This impacted negative numbers of pattern -0.00XX.
-0.00XX (#458) (824939a)
We invite you to try the bson library immediately, and report any issues to the NODE project.
The MongoDB Node.js team is pleased to announce version 4.5.1 of the bson module!
The MongoDB Node.js team is pleased to announce version 4.5.1 of the bson module!
In react native environments there was an issue where the bundler attempted to import the Node.js polyfill for 'util'.
We no longer depend on the package.
We invite you to try the bson library immediately, and report any issues to the NODE project.
Your coding agent can read these notes before it upgrades. Set up the MCP server →