low-json-db

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:

  1. Adds the document to the in-memory array
  2. Updates the indexes (if any)
  3. Writes the entire array to a temporary file (users.tmp.json)
  4. 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

Next: Learn how to query documents.