Inserting Documents
Inserting is the process of adding new documents into a collection. low-json-db supports both single and bulk inserts, with automatic ID generation.
Insert One Document
const user = users.insert({
name: 'Alice',
email: 'alice@example.com',
age: 28,
tags: ['admin']
});
console.log(user);
// {
// name: 'Alice',
// email: 'alice@example.com',
// age: 28,
// tags: ['admin'],
// _id: 1
// }
If autoId: true was set when creating the collection,
an _id is automatically added (unless the document already has one).
Insert Many Documents
const inserted = users.insertMany([
{ name: 'Bob', email: 'bob@example.com', age: 34 },
{ name: 'Carol', email: 'carol@example.com', age: 22 },
{ name: 'David', email: 'david@example.com', age: 41 }
]);
console.log(inserted.length); // 3
Async Versions
For non-blocking operations (recommended in servers):
const user = await users.insertAsync({
name: 'Eve',
email: 'eve@example.com'
});
const many = await users.insertManyAsync([
{ name: 'Frank' },
{ name: 'Grace' }
]);
How Atomic Write Works
When you insert a document, the library does the following:
- Adds the document to the in-memory array
- Updates the indexes (if any)
- Writes the entire array to a temporary file (
users.tmp.json) - Atomically renames the temporary file to
users.json
This ensures that if the process crashes during the write, the original file remains intact.
Important Notes
- Documents are stored as plain JavaScript objects.
- Nested objects and arrays are fully supported.
- If you provide an
_idyourself andautoIdis true, your value is kept. - Insert operations are protected by an internal lock to avoid race conditions.
Next: Learn how to query documents.