Core binary serialization and deserialization functions for converting JavaScript objects to/from BSON format with comprehensive configuration options.
Converts a JavaScript object to BSON binary format.
/**
* Serialize a JavaScript object to BSON binary format
* @param object - The JavaScript object to serialize
* @param options - Optional serialization settings
* @returns Uint8Array containing the serialized BSON data
*/
function serialize(object: Document, options?: SerializeOptions): Uint8Array;
interface SerializeOptions {
/** Validate object keys during serialization (default: false) */
checkKeys?: boolean;
/** Include JavaScript functions in serialization (default: false) */
serializeFunctions?: boolean;
/** Ignore undefined values during serialization (default: true) */
ignoreUndefined?: boolean;
/** Minimum internal buffer size for serialization */
minInternalBufferSize?: number;
/** Starting index for serialization when using pre-allocated buffer */
index?: number;
}Usage Examples:
import { serialize, ObjectId } from "bson";
// Basic serialization
const document = { name: "Alice", age: 30 };
const bytes = serialize(document);
// Serialization with options
const complexDoc = {
_id: new ObjectId(),
data: { nested: true },
func: function() { return "hello"; },
undef: undefined
};
const strictBytes = serialize(complexDoc, {
checkKeys: true, // Validate key names
serializeFunctions: true, // Include the function
ignoreUndefined: false // Include undefined values
});Converts BSON binary data back to JavaScript objects.
/**
* Deserialize BSON binary data to JavaScript objects
* @param buffer - Uint8Array containing BSON data
* @param options - Optional deserialization settings
* @returns Deserialized JavaScript object
*/
function deserialize(buffer: Uint8Array, options?: DeserializeOptions): Document;
interface DeserializeOptions {
/** Use native BigInt for 64-bit integers (default: false) */
useBigInt64?: boolean;
/** Promote Long values to JavaScript numbers when safe (default: true) */
promoteLongs?: boolean;
/** Promote Buffer objects to Uint8Array (default: false) */
promoteBuffers?: boolean;
/** Promote BSON values to native JavaScript types when possible (default: true) */
promoteValues?: boolean;
/** Specify fields to return as raw Buffer objects */
fieldsAsRaw?: Document;
/** Return BSONRegExp objects instead of native RegExp (default: false) */
bsonRegExp?: boolean;
/** Allow objects smaller than buffer size (for stream parsing) */
allowObjectSmallerThanBufferSize?: boolean;
/** Starting index for deserialization */
index?: number;
/** Return raw BSON bytes for fields (internal use) */
raw?: boolean;
/** UTF-8 validation settings */
validation?: {
utf8?: boolean | Record<string, true> | Record<string, false>;
};
}Usage Examples:
import { serialize, deserialize, Long } from "bson";
// Basic deserialization
const bytes = serialize({ count: 42, active: true });
const restored = deserialize(bytes);
// Result: { count: 42, active: true }
// Deserialization with type promotion control
const docWithLong = { bigNumber: Long.fromString("9223372036854775807") };
const serialized = serialize(docWithLong);
// Promote Long to number when safe
const promoted = deserialize(serialized, { promoteLongs: true });
// Keep as Long object
const exact = deserialize(serialized, { promoteLongs: false });Serializes directly into a pre-allocated buffer for performance optimization.
/**
* Serialize into a pre-allocated buffer
* @param object - The JavaScript object to serialize
* @param finalBuffer - Pre-allocated Uint8Array to write into
* @param options - Optional serialization settings
* @returns Index pointing to the last written byte
*/
function serializeWithBufferAndIndex(
object: Document,
finalBuffer: Uint8Array,
options?: SerializeOptions
): number;Usage Example:
import { serializeWithBufferAndIndex } from "bson";
// Pre-allocate a large buffer for multiple serializations
const buffer = new Uint8Array(1024);
const doc1 = { name: "First" };
const doc2 = { name: "Second" };
// Serialize first document at the beginning
const index1 = serializeWithBufferAndIndex(doc1, buffer, { index: 0 });
// Serialize second document after the first
const index2 = serializeWithBufferAndIndex(doc2, buffer, { index: index1 + 1 });Calculates the BSON byte size without performing actual serialization.
/**
* Calculate the BSON byte size for a JavaScript object
* @param object - The JavaScript object to calculate size for
* @param options - Optional calculation settings
* @returns Size of BSON object in bytes
*/
function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number;
type CalculateObjectSizeOptions = Pick<SerializeOptions, 'serializeFunctions' | 'ignoreUndefined'>;Usage Example:
import { calculateObjectSize, serialize } from "bson";
const document = {
_id: new ObjectId(),
title: "Sample Document",
tags: ["mongodb", "bson", "javascript"]
};
// Calculate size without serializing
const estimatedSize = calculateObjectSize(document);
console.log(`Document will be ${estimatedSize} bytes when serialized`);
// Verify with actual serialization
const actualBytes = serialize(document);
console.log(`Actual size: ${actualBytes.length} bytes`);
// Both values should matchDeserializes multiple BSON documents from a continuous data stream.
/**
* Deserialize multiple BSON documents from stream data
* @param data - Buffer containing serialized BSON documents
* @param startIndex - Starting index in the buffer
* @param numberOfDocuments - Number of documents to deserialize
* @param documents - Array to store deserialized documents
* @param docStartIndex - Starting index in documents array
* @param options - Deserialization options
* @returns Next index in buffer after deserialization
*/
function deserializeStream(
data: Uint8Array | ArrayBuffer,
startIndex: number,
numberOfDocuments: number,
documents: Document[],
docStartIndex: number,
options: DeserializeOptions
): number;Usage Example:
import { serialize, deserializeStream } from "bson";
// Create a stream of multiple serialized documents
const doc1 = { name: "Alice", type: "user" };
const doc2 = { name: "Bob", type: "admin" };
const doc3 = { name: "Charlie", type: "user" };
const bytes1 = serialize(doc1);
const bytes2 = serialize(doc2);
const bytes3 = serialize(doc3);
// Combine into a single buffer (simulating a stream)
const stream = new Uint8Array(bytes1.length + bytes2.length + bytes3.length);
stream.set(bytes1, 0);
stream.set(bytes2, bytes1.length);
stream.set(bytes3, bytes1.length + bytes2.length);
// Deserialize multiple documents from the stream
const documents: Document[] = [];
const nextIndex = deserializeStream(
stream,
0, // Start at beginning
3, // Read 3 documents
documents, // Store results here
0, // Start storing at index 0
{ promoteValues: true }
);
console.log(documents); // [{ name: "Alice", type: "user" }, ...]Controls the internal buffer size used for serialization operations.
/**
* Set the size of the internal serialization buffer
* @param size - Desired buffer size in bytes
*/
function setInternalBufferSize(size: number): void;Usage Example:
import { setInternalBufferSize, serialize } from "bson";
// Increase buffer size for large document serialization
setInternalBufferSize(10 * 1024 * 1024); // 10MB buffer
// Now serialize large documents more efficiently
const largeDocument = {
data: new Array(100000).fill({ field: "value", nested: { deep: true } })
};
const bytes = serialize(largeDocument);interface Document {
[key: string]: any;
}