Intermediate LevelMongoDB & Mongoose
How do you run multi-document transactions using Mongoose ClientSession?
❓ Interview Prompt: Explain Mongoose session management, withTransaction helper, automatic retry handling, and aborting failed transactions.
Mongoose provides a convenience helper 'session.withTransaction()' that automates starting transactions, committing state, and retrying on transient commit errors:
Code Implementation Example
typescript
import mongoose from 'mongoose';
import { OrderModel } from './models/Order';
import { InventoryModel } from './models/Inventory';
async function placeOrderTxn(userId: string, productId: string) {
const session = await mongoose.startSession();
try {
await session.withTransaction(async () => {
await OrderModel.create([{ userId, productId }], { session });
await InventoryModel.updateOne({ productId }, { $inc: { stock: -1 } }, { session });
});
} finally {
session.endSession();
}
}💡Executing Mongoose multi-document transactions using session.withTransaction().
🎯 Interview Key Takeaway
Use session.withTransaction() to automate commit retry logic and transaction error handling in Mongoose.
#withTransaction#Mongoose Session#ACID#Intermediate
Back to all MongoDB & Mongoose Questions→