Challenge 2: Write the Checkout Transaction — Possible Solution ==================================================================== const session = client.startSession(); try { await session.withTransaction(async () => { await orders.insertOne( { _id: new ObjectId(), product_id: "P200", customer_id: "C104", quantity: 1, status: "placed" }, { session } ); await products.updateOne( { _id: "P200" }, { $inc: { stock: -1 } }, { session } ); }); } finally { session.endSession(); } WHY THIS WORKS AS AN ANSWER ------------------------------ startSession() creates the session both operations will share, and endSession() runs in a finally block so the session is always cleaned up, whether the transaction committed or was aborted. withTransaction() wraps the callback: if BOTH insertOne and updateOne succeed, it commits automatically; if either one throws (for example, a driver-level error, or application logic that rejects the order because stock is already 0), it aborts the WHOLE transaction automatically — the order insert is rolled back even though it may have technically already run and "succeeded" in isolation. Every single operation inside the callback passes { session } as its options argument — this is what actually ties each write to the transaction. Forgetting it on either call (an easy mistake) would mean that operation runs OUTSIDE the transaction, immediately and permanently, regardless of what happens to the rest of the block. Using withTransaction() here rather than manual startTransaction()/commitTransaction()/catch/abortTransaction() also means transient errors (e.g. a brief replica set election) are retried automatically, per this chapter's closing gotcha.