file-json-db

Transactions

file-json-db supports snapshot transactions. All changes made inside a transaction stay in memory until you call commit(). If you call rollback() the original files on disk are left completely untouched.

How it works

  1. You call collection.startTransaction().
  2. The library deep-clones the current in-memory index and creates an overlay for part data.
  3. Every insert / update / delete that goes through the transaction object mutates only the overlay.
  4. commit() writes the overlay to disk and updates the real index.
  5. rollback() discards the overlay; disk stays as it was.
One transaction at a time Only one transaction may be active on a given collection. Starting a second one while the first is still open throws an error.

Basic example

const tx = users.startTransaction();

try {
  tx.insert({ name: 'Alice', email: 'alice@example.com' });
  tx.insert({ name: 'Bob',   email: 'bob@example.com' });
  tx.updateOne(
    { name: 'Alice' },
    { $set: { role: 'admin' } }
  );

  // Nothing has been written to disk yet
  await tx.commit();   // now the changes become permanent
} catch (err) {
  await tx.rollback(); // discard everything
  throw err;
}

Transaction API

The transaction object exposes the same mutation methods as a collection:

When to use transactions

Limitations