Mongoose MongoDB Transaction Session

Group multi-document writes into an atomic MongoDB transaction with a session, abort on validation failure, and retry on transient errors.

JavascriptNodeData Integrity

Code

javascriptsnippet
28 lines
import mongoose from 'mongoose';

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

async function transfer(fromId, toId, amount) {
  const session = await mongoose.startSession();
  try {
    await session.withTransaction(async () => {
      const from = await Account.findById(fromId).session(session);
      const to = await Account.findById(toId).session(session);

      if (from.balance < amount) throw new Error('insufficient funds');

      from.balance -= amount;
      to.balance += amount;
      await from.save({ session });
      await to.save({ session });
    }, { readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } });
  } finally {
    await session.endSession();
  }
}

await mongoose.connect(process.env.MONGO_URI);
const receipt = await transfer('665f0a', '665f0b', 75);
console.log('transfer done:', receipt ?? 'committed');

How the snippet works

Mongoose MongoDB Transaction Session keeps everything in the function transfer.

Every asynchronous step is awaited, so rejections surface where the call happens. When the guard condition holds, Error is thrown rather than a bogus value returned.

Configuration comes from the environment — it reads MONGO_URI, so the same code switches behavior between environments without edits.

Points of care

  • mongoose must be installed first — the snippet imports it directly.
  • The guard from.balance < amount short-circuits the flow with an early throw when its condition holds.

Applying it

Signature: async function transfer(fromId, toId, amount)

The demo output is labeled (transfer done:); each label names the call that printed it.

Statements that matter

if (from.balance < amount) throw new Error('insufficient funds');
const from = await Account.findById(fromId).session(session);
const to = await Account.findById(toId).session(session);

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
It throws `Error` before any real work runs, via the guard `from.balance < amount` — handle it at the call site or let it propagate deliberately.
Are there third-party dependencies?
`mongoose` — install it with the package manager before running.