Binary (type 5) stores raw bytes plus a one-byte subtype saying what they mean: 0x00 generic, 0x04 UUID, 0x05 MD5, 0x06 a value written by client-side field-level encryption, 0x80 and above yours. A thumbnail, a password hash, a protobuf payload or a PDF under the size limit all belong here — never base64 inside a string, which inflates the bytes by a third and hides the type. The UUID class is Binary subtype 4 with a friendlier face; store UUIDs that way, not as 36-character strings.
import { serialize, deserialize, Binary, UUID, BSONRegExp, Code, Timestamp,
DBRef, MinKey, MaxKey, ObjectId, EJSON } from 'bson';
const u = new UUID();
console.log('uuid :', u.toHexString(true), '| subtype', u.sub_type, '| blob :',
Binary.createFromBase64('SGVsbG8gTU9OR08=', 0).toString('utf8'));
const out = deserialize(serialize({ id: u, re: new BSONRegExp('^mongo', 'i'),
code: new Code('function () { return this.x; }'), ts: new Timestamp({ t: 1758500000, i: 1 }),
ref: new DBRef('authors', new ObjectId()), lo: new MinKey(), hi: new MaxKey() }));
console.log('types :', Object.values(out).map((v) => v.constructor.name).join(' '));
console.log('EJSON :', EJSON.stringify({ id: u }));uuid : f0c53529-a92f-486b-a3d4-22ba3cb58372 | subtype 4 | blob : Hello MONGO
types : UUID RegExp Code Timestamp DBRef MinKey MaxKey
EJSON : {"id":{"$binary":{"base64":"8MU1KakvSGuj1CK6PLWDcg==","subType":"04"}}}| Type | Code | $type alias | Node class |
|---|---|---|---|
| Double, String | 1, 2 | double, string | Number/Double, String |
| Object, Array | 3, 4 | object, array | Object, Array |
| Binary, ObjectId | 5, 7 | binData, objectId | Binary/UUID, ObjectId |
| Bool, Null, Date | 8, 10, 9 | bool, null, date | Boolean, null, Date |
| Regex, JavaScript | 11, 13 | regex, javascript | BSONRegExp, Code |
| Int32, Long, Decimal | 16, 18, 19 | int, long, decimal | Int32, Long, Decimal128 |
| Timestamp, Min, Max | 17, -1, 127 | timestamp, minKey, maxKey | Timestamp, MinKey, MaxKey |
Four types are deprecated and should never appear in new data: undefined (6), dbPointer (12), symbol (14) and javascriptWithScope (15). MinKey and MaxKey sort below and above every other value — useful as range and shard-key bounds, not as stored data. DBRef is a convention, not a feature: a { $ref, $id, $db } subdocument drivers recognize but the server never resolves, so prefer a plain ObjectId field with $lookup ($lookup).