UNPKG

15.9 kBMarkdownView Raw
1# BSON parser
2
3BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in [the specification](http://bsonspec.org).
4
5This browser version of the BSON parser is compiled using [rollup](https://rollupjs.org/) and the current version is pre-compiled in the `dist` directory.
6
7This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext).
8
9### Table of Contents
10- [Usage](#usage)
11- [Bugs/Feature Requests](#bugs--feature-requests)
12- [Installation](#installation)
13- [Documentation](#documentation)
14- [FAQ](#faq)
15
16## Bugs / Feature Requests
17
18Think you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA:
19
201. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org)
212. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE)
223. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it.
23
24Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are **public**.
25
26## Usage
27
28To build a new version perform the following operations:
29
30```
31npm install
32npm run build
33```
34
35### Node (no bundling)
36A simple example of how to use BSON in `Node.js`:
37
38```js
39const BSON = require('bson');
40const Long = BSON.Long;
41
42// Serialize a document
43const doc = { long: Long.fromNumber(100) };
44const data = BSON.serialize(doc);
45console.log('data:', data);
46
47// Deserialize the resulting Buffer
48const doc_2 = BSON.deserialize(data);
49console.log('doc_2:', doc_2);
50```
51
52### Browser (no bundling)
53
54If you are not using a bundler like webpack, you can include `dist/bson.bundle.js` using a script tag. It includes polyfills for built-in node types like `Buffer`.
55
56```html
57<script src="./dist/bson.bundle.js"></script>
58
59<script>
60 function start() {
61 // Get the Long type
62 const Long = BSON.Long;
63
64 // Serialize a document
65 const doc = { long: Long.fromNumber(100) }
66 const data = BSON.serialize(doc);
67 console.log('data:', data);
68
69 // De serialize it again
70 const doc_2 = BSON.deserialize(data);
71 console.log('doc_2:', doc_2);
72 }
73</script>
74```
75
76### Using webpack
77
78If using webpack, you can use your normal import/require syntax of your project to pull in the `bson` library.
79
80ES6 Example:
81
82```js
83import { Long, serialize, deserialize } from 'bson';
84
85// Serialize a document
86const doc = { long: Long.fromNumber(100) };
87const data = serialize(doc);
88console.log('data:', data);
89
90// De serialize it again
91const doc_2 = deserialize(data);
92console.log('doc_2:', doc_2);
93```
94
95ES5 Example:
96
97```js
98const BSON = require('bson');
99const Long = BSON.Long;
100
101// Serialize a document
102const doc = { long: Long.fromNumber(100) };
103const data = BSON.serialize(doc);
104console.log('data:', data);
105
106// Deserialize the resulting Buffer
107const doc_2 = BSON.deserialize(data);
108console.log('doc_2:', doc_2);
109```
110
111Depending on your settings, webpack will under the hood resolve to one of the following:
112
113- `dist/bson.browser.esm.js` If your project is in the browser and using ES6 modules (Default for `webworker` and `web` targets)
114- `dist/bson.browser.umd.js` If your project is in the browser and not using ES6 modules
115- `dist/bson.esm.js` If your project is in Node.js and using ES6 modules (Default for `node` targets)
116- `lib/bson.js` (the normal include path) If your project is in Node.js and not using ES6 modules
117
118For more information, see [this page on webpack's `resolve.mainFields`](https://webpack.js.org/configuration/resolve/#resolvemainfields) and [the `package.json` for this project](./package.json#L52)
119
120### Usage with Angular
121
122Starting with Angular 6, Angular CLI removed the shim for `global` and other node built-in variables (original comment [here](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063)). If you are using BSON with Angular, you may need to add the following shim to your `polyfills.ts` file:
123
124```js
125// In polyfills.ts
126(window as any).global = window;
127```
128
129- [Original Comment by Angular CLI](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063)
130- [Original Source for Solution](https://stackoverflow.com/a/50488337/4930088)
131
132## Installation
133
134`npm install bson`
135
136## Documentation
137
138### Objects
139
140<dl>
141<dt><a href="#EJSON">EJSON</a> : <code>object</code></dt>
142<dd></dd>
143</dl>
144
145### Functions
146
147<dl>
148<dt><a href="#setInternalBufferSize">setInternalBufferSize(size)</a></dt>
149<dd><p>Sets the size of the internal serialization buffer.</p>
150</dd>
151<dt><a href="#serialize">serialize(object)</a><code>Buffer</code></dt>
152<dd><p>Serialize a Javascript object.</p>
153</dd>
154<dt><a href="#serializeWithBufferAndIndex">serializeWithBufferAndIndex(object, buffer)</a><code>Number</code></dt>
155<dd><p>Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.</p>
156</dd>
157<dt><a href="#deserialize">deserialize(buffer)</a><code>Object</code></dt>
158<dd><p>Deserialize data as BSON.</p>
159</dd>
160<dt><a href="#calculateObjectSize">calculateObjectSize(object)</a><code>Number</code></dt>
161<dd><p>Calculate the bson size for a passed in Javascript object.</p>
162</dd>
163<dt><a href="#deserializeStream">deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options])</a><code>Number</code></dt>
164<dd><p>Deserialize stream data as BSON documents.</p>
165</dd>
166</dl>
167
168<a name="EJSON"></a>
169
170### EJSON
171
172* [EJSON](#EJSON)
173
174 * [.parse(text, [options])](#EJSON.parse)
175
176 * [.stringify(value, [replacer], [space], [options])](#EJSON.stringify)
177
178 * [.serialize(bson, [options])](#EJSON.serialize)
179
180 * [.deserialize(ejson, [options])](#EJSON.deserialize)
181
182
183<a name="EJSON.parse"></a>
184
185#### *EJSON*.parse(text, [options])
186
187| Param | Type | Default | Description |
188| --- | --- | --- | --- |
189| text | <code>string</code> | | |
190| [options] | <code>object</code> | | Optional settings |
191| [options.relaxed] | <code>boolean</code> | <code>true</code> | Attempt to return native JS types where possible, rather than BSON types (if true) |
192
193Parse an Extended JSON string, constructing the JavaScript value or object described by that
194string.
195
196**Example**
197```js
198const { EJSON } = require('bson');
199const text = '{ "int32": { "$numberInt": "10" } }';
200
201// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
202console.log(EJSON.parse(text, { relaxed: false }));
203
204// prints { int32: 10 }
205console.log(EJSON.parse(text));
206```
207<a name="EJSON.stringify"></a>
208
209#### *EJSON*.stringify(value, [replacer], [space], [options])
210
211| Param | Type | Default | Description |
212| --- | --- | --- | --- |
213| value | <code>object</code> | | The value to convert to extended JSON |
214| [replacer] | <code>function</code> \| <code>array</code> | | 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 |
215| [space] | <code>string</code> \| <code>number</code> | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. |
216| [options] | <code>object</code> | | Optional settings |
217| [options.relaxed] | <code>boolean</code> | <code>true</code> | Enabled Extended JSON's `relaxed` mode |
218| [options.legacy] | <code>boolean</code> | <code>true</code> | Output in Extended JSON v1 |
219
220Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
221function is specified or optionally including only the specified properties if a replacer array
222is specified.
223
224**Example**
225```js
226const { EJSON } = require('bson');
227const Int32 = require('mongodb').Int32;
228const doc = { int32: new Int32(10) };
229
230// prints '{"int32":{"$numberInt":"10"}}'
231console.log(EJSON.stringify(doc, { relaxed: false }));
232
233// prints '{"int32":10}'
234console.log(EJSON.stringify(doc));
235```
236<a name="EJSON.serialize"></a>
237
238#### *EJSON*.serialize(bson, [options])
239
240| Param | Type | Description |
241| --- | --- | --- |
242| bson | <code>object</code> | The object to serialize |
243| [options] | <code>object</code> | Optional settings passed to the `stringify` function |
244
245Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
246
247<a name="EJSON.deserialize"></a>
248
249#### *EJSON*.deserialize(ejson, [options])
250
251| Param | Type | Description |
252| --- | --- | --- |
253| ejson | <code>object</code> | The Extended JSON object to deserialize |
254| [options] | <code>object</code> | Optional settings passed to the parse method |
255
256Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
257
258<a name="setInternalBufferSize"></a>
259
260### setInternalBufferSize(size)
261
262| Param | Type | Description |
263| --- | --- | --- |
264| size | <code>number</code> | The desired size for the internal serialization buffer |
265
266Sets the size of the internal serialization buffer.
267
268<a name="serialize"></a>
269
270### serialize(object)
271
272| Param | Type | Default | Description |
273| --- | --- | --- | --- |
274| object | <code>Object</code> | | the Javascript object to serialize. |
275| [options.checkKeys] | <code>Boolean</code> | | the serializer will check if keys are valid. |
276| [options.serializeFunctions] | <code>Boolean</code> | <code>false</code> | serialize the javascript functions **(default:false)**. |
277| [options.ignoreUndefined] | <code>Boolean</code> | <code>true</code> | ignore undefined fields **(default:true)**. |
278
279Serialize a Javascript object.
280
281**Returns**: <code>Buffer</code> - returns the Buffer object containing the serialized object.
282<a name="serializeWithBufferAndIndex"></a>
283
284### serializeWithBufferAndIndex(object, buffer)
285
286| Param | Type | Default | Description |
287| --- | --- | --- | --- |
288| object | <code>Object</code> | | the Javascript object to serialize. |
289| buffer | <code>Buffer</code> | | the Buffer you pre-allocated to store the serialized BSON object. |
290| [options.checkKeys] | <code>Boolean</code> | | the serializer will check if keys are valid. |
291| [options.serializeFunctions] | <code>Boolean</code> | <code>false</code> | serialize the javascript functions **(default:false)**. |
292| [options.ignoreUndefined] | <code>Boolean</code> | <code>true</code> | ignore undefined fields **(default:true)**. |
293| [options.index] | <code>Number</code> | | the index in the buffer where we wish to start serializing into. |
294
295Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.
296
297**Returns**: <code>Number</code> - returns the index pointing to the last written byte in the buffer.
298<a name="deserialize"></a>
299
300### deserialize(buffer)
301
302| Param | Type | Default | Description |
303| --- | --- | --- | --- |
304| buffer | <code>Buffer</code> | | the buffer containing the serialized set of BSON documents. |
305| [options.evalFunctions] | <code>Object</code> | <code>false</code> | evaluate functions in the BSON document scoped to the object deserialized. |
306| [options.cacheFunctions] | <code>Object</code> | <code>false</code> | cache evaluated functions for reuse. |
307| [options.promoteLongs] | <code>Object</code> | <code>true</code> | when deserializing a Long will fit it into a Number if it's smaller than 53 bits |
308| [options.promoteBuffers] | <code>Object</code> | <code>false</code> | when deserializing a Binary will return it as a node.js Buffer instance. |
309| [options.promoteValues] | <code>Object</code> | <code>false</code> | when deserializing will promote BSON values to their Node.js closest equivalent types. |
310| [options.fieldsAsRaw] | <code>Object</code> | <code></code> | allow to specify if there what fields we wish to return as unserialized raw buffer. |
311| [options.bsonRegExp] | <code>Object</code> | <code>false</code> | return BSON regular expressions as BSONRegExp instances. |
312| [options.allowObjectSmallerThanBufferSize] | <code>boolean</code> | <code>false</code> | allows the buffer to be larger than the parsed BSON object |
313
314Deserialize data as BSON.
315
316**Returns**: <code>Object</code> - returns the deserialized Javascript Object.
317<a name="calculateObjectSize"></a>
318
319### calculateObjectSize(object)
320
321| Param | Type | Default | Description |
322| --- | --- | --- | --- |
323| object | <code>Object</code> | | the Javascript object to calculate the BSON byte size for. |
324| [options.serializeFunctions] | <code>Boolean</code> | <code>false</code> | serialize the javascript functions **(default:false)**. |
325| [options.ignoreUndefined] | <code>Boolean</code> | <code>true</code> | ignore undefined fields **(default:true)**. |
326
327Calculate the bson size for a passed in Javascript object.
328
329**Returns**: <code>Number</code> - returns the number of bytes the BSON object will take up.
330<a name="deserializeStream"></a>
331
332### deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options])
333
334| Param | Type | Default | Description |
335| --- | --- | --- | --- |
336| data | <code>Buffer</code> | | the buffer containing the serialized set of BSON documents. |
337| startIndex | <code>Number</code> | | the start index in the data Buffer where the deserialization is to start. |
338| numberOfDocuments | <code>Number</code> | | number of documents to deserialize. |
339| documents | <code>Array</code> | | an array where to store the deserialized documents. |
340| docStartIndex | <code>Number</code> | | the index in the documents array from where to start inserting documents. |
341| [options] | <code>Object</code> | | additional options used for the deserialization. |
342| [options.evalFunctions] | <code>Object</code> | <code>false</code> | evaluate functions in the BSON document scoped to the object deserialized. |
343| [options.cacheFunctions] | <code>Object</code> | <code>false</code> | cache evaluated functions for reuse. |
344| [options.promoteLongs] | <code>Object</code> | <code>true</code> | when deserializing a Long will fit it into a Number if it's smaller than 53 bits |
345| [options.promoteBuffers] | <code>Object</code> | <code>false</code> | when deserializing a Binary will return it as a node.js Buffer instance. |
346| [options.promoteValues] | <code>Object</code> | <code>false</code> | when deserializing will promote BSON values to their Node.js closest equivalent types. |
347| [options.fieldsAsRaw] | <code>Object</code> | <code></code> | allow to specify if there what fields we wish to return as unserialized raw buffer. |
348| [options.bsonRegExp] | <code>Object</code> | <code>false</code> | return BSON regular expressions as BSONRegExp instances. |
349
350Deserialize stream data as BSON documents.
351
352**Returns**: <code>Number</code> - returns the next index in the buffer after deserialization **x** numbers of documents.
353
354## FAQ
355
356#### Why does `undefined` get converted to `null`?
357
358The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys.
359
360#### How do I add custom serialization logic?
361
362This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize.
363
364```javascript
365const BSON = require('bson');
366
367class CustomSerialize {
368 toBSON() {
369 return 42;
370 }
371}
372
373const obj = { answer: new CustomSerialize() };
374// "{ answer: 42 }"
375console.log(BSON.deserialize(BSON.serialize(obj)));
376```