Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

BSON Parser for node and browser

License

NotificationsYou must be signed in to change notification settings

mongodb/js-bson

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents.You can learn more about it inthe specification.

Table of Contents

Release Integrity

Releases are created automatically and signed using theNode team's GPG key. This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:

gpg --import node-driver.asc

The GitHub release contains a detached signature file for the NPM package (namedbson-X.Y.Z.tgz.sig).

The following command returns the link npm package.

npm view bson@vX.Y.Z dist.tarball

Using the result of the above command, acurl 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 verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.

Bugs / Feature Requests

Think you've found a bug? Want to see a new feature inbson? Please open a case in our issue management tool, JIRA:

  1. Create an account and login:jira.mongodb.org
  2. Navigate to the NODE project:jira.mongodb.org/browse/NODE
  3. ClickCreate Issue - Please provide as much information as possible about the issue and how to reproduce it.

Bug reports in JIRA for the NODE driver project arepublic.

Usage

To build a new version perform the following operations:

npm installnpm run build

Node.js or Bundling Usage

When 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');constbytes=BSON.serialize({_id:newObjectId()});console.log(bytes);constdoc=BSON.deserialize(bytes);console.log(EJSON.stringify(doc));// {"_id":{"$oid":"..."}}

Browser Usage

If you are working directly in the browser without a bundler please use the.mjs bundle like so:

<scripttype="module">import{BSON,EJSON,ObjectId}from'./lib/bson.mjs';constbytes=BSON.serialize({_id:newObjectId()});console.log(bytes);constdoc=BSON.deserialize(bytes);console.log(EJSON.stringify(doc));// {"_id":{"$oid":"..."}}</script>

Installation

npm install bson

MongoDB Node.js Driver Version Compatibility

Only the following version combinations with theMongoDB Node.js Driver are considered stable.

bson@1.xbson@4.xbson@5.xbson@6.x
mongodb@6.xN/AN/AN/A
mongodb@5.xN/AN/AN/A
mongodb@4.xN/AN/AN/A
mongodb@3.xN/AN/AN/A

Documentation

BSON

API documentation

EJSON

EJSON.parse(text, [options])

ParamTypeDefaultDescription
textstring
[options]objectOptional settings
[options.relaxed]booleantrueAttempt 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 thatstring.

Example

const{EJSON}=require('bson');consttext='{ "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));

EJSON.stringify(value, [replacer], [space], [options])

ParamTypeDefaultDescription
valueobjectThe value to convert to extended JSON
[replacer]function |arrayA 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 |numberA String or Number object that's used to insert white space into the output JSON string for readability purposes.
[options]objectOptional settings
[options.relaxed]booleantrueEnabled Extended JSON'srelaxed mode
[options.legacy]booleantrueOutput in Extended JSON v1

Converts a BSON document to an Extended JSON string, optionally replacing values if a replacerfunction is specified or optionally including only the specified properties if a replacer arrayis specified.

Example

const{EJSON}=require('bson');constInt32=require('mongodb').Int32;constdoc={int32:newInt32(10)};// prints '{"int32":{"$numberInt":"10"}}'console.log(EJSON.stringify(doc,{relaxed:false}));// prints '{"int32":10}'console.log(EJSON.stringify(doc));

EJSON.serialize(bson, [options])

ParamTypeDescription
bsonobjectThe object to serialize
[options]objectOptional settings passed to thestringify function

Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.

EJSON.deserialize(ejson, [options])

ParamTypeDescription
ejsonobjectThe Extended JSON object to deserialize
[options]objectOptional settings passed to the parse method

Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types

Error Handling

It is our recommendation to useBSONError.isBSONError() checks on errors and to avoid relying on parsingerror.message anderror.name strings in your code. We guaranteeBSONError.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 meansBSONError.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:

letdocumentCount=0;constcursor=collection.find({},{utf8Validation:true});try{forawait(constdocofcursor)documentCount+=1;}catch(error){if(BSONError.isBSONError(error)){console.log(`Found the troublemaker UTF-8!:${documentCount}${error.message}`);returndocumentCount;}throwerror;}

React Native

BSON vendors the required polyfills forTextEncoder,TextDecoder,atob,btoa imported from React Native and therefore doesn't expect users to polyfill these. One additional polyfill,crypto.getRandomValues is recommended and can be installed with the following command:

npm install --save react-native-get-random-values

The following snippet should be placed at the top of the entrypoint (by default this is the rootindex.js file) for React Native projects using the BSON library. These lines must be placed for any code that importsBSON.

// Required Polyfills For ReactNativeimport'react-native-get-random-values';

Finally, import theBSON library like so:

import{BSON,EJSON}from'bson';

This will cause React Native to import thenode_modules/bson/lib/bson.rn.cjs bundle (see the"react-native" setting we have in the"exports" section of ourpackage.json.)

Technical Note about React Native module import

The"exports" definition in ourpackage.json will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax inReact Native's runtime hermes.

FAQ

Why doesundefined get converted tonull?

Theundefined BSON type has beendeprecated for many years, so this library has dropped support for it. Use theignoreUndefined option (for example, from thedriver ) to instead removeundefined keys.

How do I add custom serialization logic?

This library looks fortoBSON() functions on every path, and calls thetoBSON() function to get the value to serialize.

constBSON=require('bson');classCustomSerialize{toBSON(){return42;}}constobj={answer:newCustomSerialize()};// "{ answer: 42 }"console.log(BSON.deserialize(BSON.serialize(obj)));

[8]ページ先頭

©2009-2025 Movatter.jp