BSON Parser for node and browser
BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in the specification.
Releases are created automatically and signed using the Node team's GPG key. All release packages provided as part of a GitHub release are signed. To verify the provided packages, download the key and import it using gpg:
gpg --import node-driver.ascThe GitHub release contains a detached signature file for the NPM package (named
bson-X.Y.Z.tgz.sig).
The following command returns the link npm package.
npm view [email protected] dist.tarball Using the result of the above command, a curl command can return the official npm package for the release.
To verify the integrity of the downloaded package, run the following command:
gpg --verify bson-X.Y.Z.tgz.sig bson-X.Y.Z.tgz[!Note] No GPG verification is done when using npm to install the package. The contents of the GitHub tarball and npm's tarball are identical.
Releases published to the npm registry also include a provenance attestation, which cryptographically links the package to its source repository and build workflow. To verify provenance:
npm audit signaturesThink you've found a bug? Want to see a new feature in bson? Please open a case in our issue management tool, JIRA:
Bug reports in JIRA for the NODE driver project are public.
To build a new version perform the following operations:
npm install
npm run buildWhen using a bundler or Node.js you can import bson using the package name:
import { BSON, EJSON, ObjectId } from 'bson';
// or:
// const { BSON, EJSON, ObjectId } = require('bson');
const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
// {"_id":{"$oid":"..."}}If you are working directly in the browser without a bundler please use the .mjs bundle like so:
This repository uses agentskills.io conventions for AI coding agent
instructions. AGENTS.md is the canonical source of truth — tool-specific files like CLAUDE.md
are generated references.
AGENTS.md in the target directory.git add the file.scripts/symlink-claude-md.sh to generate the companion CLAUDE.md.scripts/symlink-claude-md.sh is vendored from an internal repo and should not be edited directly.npm install bsonOnly the following version combinations with the MongoDB Node.js Driver are considered stable.
[email protected] |
[email protected] |
[email protected] |
[email protected] |
[email protected] |
|
|---|---|---|---|---|---|
[email protected] |
N/A | N/A | N/A | N/A | ✓ |
[email protected] |
N/A | N/A | N/A | ✓ | N/A |
[email protected] |
N/A | N/A | ✓ | N/A | N/A |
[email protected] |
N/A | ✓ | N/A | N/A | N/A |
[email protected] |
✓ | N/A | N/A | N/A | N/A |
| Param | Type | Default | Description |
|---|---|---|---|
| text | string | ||
| [options] | object | Optional settings | |
| [options.relaxed] | boolean | true | Attempt to return native JS types where possible, rather than BSON types (if true) |
Parse an Extended JSON string, constructing the JavaScript value or object described by that string.
[!WARNING] If you use the result of
EJSON.parse()in a query, update, or command, an attacker can inject operators or unexpected field values that change the meaning of the operation. This risk is greatest when the input text originates from a source that your application does not control. Validate untrusted input before parsing it. To learn more about validating input before conversion and other security best practices for client libraries, see the Client Libraries Best Practices page in the MongoDB documentation.
Example
const { EJSON } = require('bson');
const text = '{ "int32": { "$numberInt": "10" } }';
// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
console.log(EJSON.parse(text, { relaxed: false }));
// prints { int32: 10 }
console.log(EJSON.parse(text));| Param | Type | Default | Description |
|---|---|---|---|
| value | object | The value to convert to extended JSON | |
| [replacer] | function | array | A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string | |
| [space] | string | number | A String or Number object that's used to insert white space into the output JSON string for readability purposes. | |
| [options] | object | Optional settings | |
| [options.relaxed] | boolean | true | Enabled Extended JSON's relaxed mode |
| [options.legacy] | boolean | true | Output in Extended JSON v1 |
Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Example
const { EJSON } = require('bson');
const Int32 = require('mongodb').Int32;
const doc = { int32: new Int32(10) };
// prints '{"int32":{"$numberInt":"10"}}'
console.log(EJSON.stringify(doc, { relaxed: false }));
// prints '{"int32":10}'
console.log(EJSON.stringify(doc));| Param | Type | Description |
|---|---|---|
| bson | object | The object to serialize |
| [options] | object | Optional settings passed to the stringify function |
Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
| Param | Type | Description |
|---|---|---|
| ejson | object | The Extended JSON object to deserialize |
| [options] | object | Optional settings passed to the parse method |
Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
It is our recommendation to use BSONError.isBSONError() checks on errors and to avoid relying on parsing error.message and error.name strings in your code. We guarantee BSONError.isBSONError() checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.
Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.
This means BSONError.isBSONError() will always be able to accurately capture the errors that our BSON library throws.
Hypothetical example: A collection in our Db has an issue with UTF-8 data:
let documentCount = 0;
const cursor = collection.find({}, { utf8Validation: true });
try {
for await (coNo open issues yet, or sync has not completed.