Skip to content

Transactions & Batches ​

Since 2.10, several writes can be done all or nothing. Every write still goes through the normal rules: grants, access rules, before-hooks, validation and behaviours. Transactions need a replica set or a sharded cluster. Without one the answer is 501 (code 5012); the writes are never silently done one by one.

In server code ​

ts
// server/api/checkout.post.ts
export default defineEventHandler(event => useMongocampTransaction(async (tx) => {
  const order = await tx.collection('orders', { user: event }).insert({ item: 'book', qty: 1 })
  await tx.collection('stock', { user: 'system' }).updateMany({ item: 'book' }, { reserved: true })
  return order
}))
  • tx.collection(name, { user }) is a server collection whose reads and writes all run in the transaction. Reads see the transaction's own writes.
  • If the function throws, everything is rolled back.
  • The events of the writes (Nitro hooks, audit records, live updates, webhooks) are published after the commit only. An aborted transaction publishes nothing.
  • Since 3.0 the events of a transaction are committed with its writes (an outbox, mc_outbox, only events that have a listener): if the server stops between the commit and the publishing, the next dispatch (every OUTBOX_INTERVAL, default 30 s, also on another instance) publishes them, in the order of the writes. A listener gets an event at least once.
  • The driver retries transient errors, so the function may run more than once.
  • tx.session lets driver calls of the application take part: { session: tx.session }. Before-hooks get the session as event.session.

Without Nuxt, use server.transaction(async tx => …) on the core.

Over HTTP: POST /mongodb/batch ​

json
{
  "atomic": true,
  "operations": [
    { "op": "insert", "collection": "orders", "document": { "item": "book", "qty": 1 } },
    { "op": "update", "collection": "stock", "id": "6650…", "document": { "count": 4 } },
    { "op": "delete", "collection": "carts", "id": "6651…" }
  ]
}
  • Operations: insert (document), replace (id, document), update (id, document holding the fields to set; null removes a field) and delete (id). Documents are Extended JSON.
  • atomic: true (the default): one transaction. A failing operation fails the whole request, and the message names the operation (operation 2 (insert orders): …).
  • atomic: false: the operations run one after another, and each result is reported ({ ok: false, error } for a failure).
  • Size: at most 1000 operations per batch (413, code 4134).

On the client:

ts
const { run } = useMongocampBatch()
await run([
  { op: 'insert', collection: 'orders', document: { item: 'book', qty: 1 } },
  { op: 'update', collection: 'stock', id: stockItem, document: { count: 4 } },
])

Released under the MIT License.