Transactions
Transactions group multiple operations into a single commit.
db.transaction(fn)
transaction<T>(fn: (tx: DBTransactionContext) => Promise<T>): Promise<T>
- Runs
fn(tx), records operations to the write-ahead log (WAL), then commits. - If the manager/db is in readonly mode, transactions are rejected.
What you can do inside a transaction
Inside fn, use tx.collection("<name>") and then call the same collection operations you’d use normally.
- TypeScript
- JavaScript
import { LioranManager } from "@liorandb/core";
const manager = new LioranManager({ rootPath: "./data" });
const db = await manager.db("app");
await db.transaction(async (tx) => {
const accounts = tx.collection<{ _id?: string; id: string; balance: number }>("accounts");
await accounts.updateOne({ id: "a" }, { $inc: { balance: -50 } }, { upsert: true });
await accounts.updateOne({ id: "b" }, { $inc: { balance: 50 } }, { upsert: true });
return true;
});
await manager.close();
import { LioranManager } from "@liorandb/core";
const manager = new LioranManager({ rootPath: "./data" });
const db = await manager.db("app");
await db.transaction(async (tx) => {
const accounts = tx.collection("accounts");
await accounts.updateOne({ id: "a" }, { $inc: { balance: -50 } }, { upsert: true });
await accounts.updateOne({ id: "b" }, { $inc: { balance: 50 } }, { upsert: true });
return true;
});
await manager.close();