Mongoose transactions let you group several writes across documents or collections so they either all commit or all roll back. If you have ever debited one account and crashed before crediting another, you already know why that matters. This guide shows a working pattern with Mongoose and Node.js, the replica set requirement that trips up most people locally, and the mistakes worth avoiding.

Why Mongoose transactions matter

MongoDB guarantees atomicity for a single document, so embedding related data often removes the need for a transaction. But once an operation touches multiple documents, for example an order plus inventory plus a payment record, a failure halfway leaves inconsistent data. A transaction fixes that by making the group atomic.

Mongoose transactions require a replica set

Transactions do not run on a standalone mongod. You need a replica set or a sharded cluster. MongoDB Atlas clusters already are replica sets, so this mostly affects local development and CI. If you see the error Transaction numbers are only allowed on a replica set member, your deployment is standalone or the replica set was never initiated.

Run a single-node replica set locally

A single-node replica set is enough for development. Start mongod with a replica set name, then initiate it once:

mongod --replSet rs0 --dbpath ./data

# in mongosh, once:
rs.initiate()

Then connect with the replica set in the URI. With a single node, directConnection=true is commonly needed when connecting from outside Docker:

mongodb://localhost:27017/shop?replicaSet=rs0&directConnection=true

This setup is for development only. It gives you transaction semantics but no high availability.

Your first transaction with connection.transaction()

Mongoose recommends connection.transaction(), a wrapper around the driver's session.withTransaction(). It commits when your function resolves, aborts when it throws, retries on transient transaction errors, and also resets Mongoose's change tracking after an abort, which the raw driver method does not do. Here is a transfer between two accounts:

import mongoose from 'mongoose';

const Account = mongoose.model('Account', new mongoose.Schema({
  owner: String,
  balance: { type: Number, min: 0 },
}));

export async function transfer(fromId, toId, amount) {
  await mongoose.connection.transaction(async (session) => {
    const from = await Account.findById(fromId).session(session);
    const to = await Account.findById(toId).session(session);

    if (!from || !to) throw new Error('Account not found');
    if (from.balance < amount) throw new Error('Insufficient funds');

    from.balance -= amount;
    to.balance += amount;

    await from.save({ session });
    await to.save({ session });
  });
}

If either save throws, nothing is persisted. Because the callback can be retried on transient errors, keep it free of side effects such as sending emails or calling external APIs. Do those after the transaction resolves.

Passing the session to every operation

A transaction only covers operations that carry its session. Forget it and that operation runs outside the transaction, silently. The forms are:

  • Model.create([doc], { session }) (use the array form when passing options)
  • doc.save({ session })
  • Model.findOne(...).session(session)
  • Model.aggregate([...]).session(session)

A document loaded with a session keeps it, so save() reuses it by default.

Skip passing sessions with AsyncLocalStorage

From Mongoose 8.4 you can enable automatic session propagation:

mongoose.set('transactionAsyncLocalStorage', true);

await mongoose.connection.transaction(async () => {
  await Account.updateOne({ _id: fromId }, { $inc: { balance: -amount } });
  await Account.updateOne({ _id: toId }, { $inc: { balance: amount } });
});

Operations inside the callback pick up the session without explicit arguments. This relies on the same mechanism covered in AsyncLocalStorage in Node.js. Each connection.transaction() call gets its own session, so nested transactions are independent: an inner one that succeeds is not rolled back if the outer one aborts later, though an error propagating from the inner one aborts the outer too.

Common Mongoose transactions pitfalls

  • Parallel operations. Do not use Promise.all inside a transaction. The Mongoose docs describe this as undefined behavior. Await operations sequentially.
  • Mixing APIs. Only one transaction can be active per session. Nesting session.withTransaction() inside connection.transaction() on the same session throws Transaction already in progress.
  • Forgetting to end manual sessions. If you use mongoose.startSession() yourself, call session.endSession() in a finally block.
  • Side effects in the callback. Retries re-run your function, so anything non-idempotent will run more than once.
  • Long transactions. Keep them short; they hold resources and increase conflict chances.

When not to use a transaction

If the data lives in one document, a single atomic update such as $inc is simpler and faster. Reserve transactions for genuine multi-document invariants. For idempotency and ordering problems in distributed flows, a transaction is not a substitute for good design, as in the token-handling concerns discussed in JWT refresh token rotation in Node.js.

Conclusion

For reliable Mongoose transactions: run a replica set, use connection.transaction(), pass the session everywhere (or enable AsyncLocalStorage), keep operations sequential, and avoid side effects inside the callback. Read the official Mongoose transactions documentation and the MongoDB Node.js driver transaction guide for the full option list.