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

snippet
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');