Collections
A collection is the basic unit of storage. It maps to a directory on disk and holds documents that share the same logical type (users, products, orders, …).
Creating a collection
const users = db.collection('users');
// or with full options
const users = db.collection({
name: 'users',
autoId: true,
idField: '_id',
idType: 'auto',
indexes: ['email', 'username'],
pretty: true,
maxPartSize: 256 * 1024,
maxRecords: 1000,
errorLevel: 'debug'
});
Collection options explained
| Option | Type | Default | Meaning |
|---|---|---|---|
name | string | required | Directory name of the collection |
autoId | boolean | false | Generate an ID when the document does not have one |
idField | string | _id | Which field holds the primary key |
idType | string | auto | auto | uuid | objectid |
indexes | string[] | [] | Fields that get secondary indexes |
pretty | boolean | true | Pretty-print JSON (indentation) |
maxPartSize | number | 256 KB | Target maximum size of a part file in bytes |
maxRecords | number | null | null | Maximum number of documents per part |
errorLevel | string | debug | debug or ignore for corrupted parts |
keepIdIndex | boolean | false | When false + idType: "auto", prefer compact range storage for the primary index (saves memory). New in 1.5.0. |
autoId and idType
When autoId is true and a document is inserted without an ID field:
idType: 'auto'→ sequential integers (1, 2, 3, …)idType: 'uuid'→ RFC-4122 UUID v4 stringsidType: 'objectid'→ 24-character hex strings similar to MongoDB ObjectIds
const orders = db.collection({
name: 'orders',
autoId: true,
idType: 'uuid'
});
const order = orders.insert({ total: 49.99 });
console.log(order._id);
// → "a3f2c1b4-9e8d-4f7a-b6c5-1d2e3f4a5b6c"
maxPartSize and maxRecords
These two options control when the library starts a new part file. A new part is created when either limit is reached.
const logs = db.collection({
name: 'logs',
maxPartSize: 512 * 1024, // 512 KB
maxRecords: 2000 // or 2000 documents
});
errorLevel
debug(default) – copy corrupted part tocrash/, emit an error, skip the partignore– silently skip the corrupted part
On-disk layout of a collection
data/
└── users/
├── index.json ← metadata + primary & secondary indexes
├── part-0001.json ← first chunk of documents
├── part-0002.json
└── crash/ ← (optional) isolated bad parts
└── part-0003.json
Collection events
Each collection is also an EventEmitter:
users.on('insert', (info) => console.log('inserted', info));
users.on('update', (info) => console.log('updated', info.count, 'docs'));
users.on('delete', (info) => console.log('deleted', info.count, 'docs'));
users.on('save', (info) => console.log('saved collection', info.collection));
users.on('error', (err) => console.error(err));
users.on('index-rebuilt', (info) => console.log('indexes rebuilt'));
users.on('transactionCommit', () => console.log('tx committed'));
users.on('transactionRollback', () => console.log('tx rolled back'));