Multi-Document Transactions
Transactions let you execute multiple operations atomically — either all succeed or all fail. This is essential for operations that must be consistent across documents.
Example
const session = await mongoose.startSession();
try {
session.startTransaction();
// Transfer money between accounts
await Account.updateOne(
{ _id: senderId },
{ $inc: { balance: -amount } },
{ session }
);
await Account.updateOne(
{ _id: receiverId },
{ $inc: { balance: amount } },
{ session }
);
// Record the transfer
await Transfer.create([{
from: senderId,
to: receiverId,
amount,
date: new Date()
}], { session });
await session.commitTransaction();
console.log('Transfer successful');
} catch (error) {
await session.abortTransaction();
console.error('Transfer failed:', error);
} finally {
session.endSession();
} When to Use Transactions
Transactions add overhead, so use them only when atomicity across documents is required.
- Financial operations (transfers, payments)
- Inventory management (order + stock update)
- User registration (create user + profile + settings)
- Any operation where partial completion would leave data inconsistent
