Exercise: Checkout Without Overselling
Write the five statements behind Riverbend Bike Shop's checkout and cancel, from a stock update that never sells a bike twice to a restock, and let the tests run two checkouts at once and a cancel inside a transaction.
Journeyman · MongoDB · Updated
Riverbend Bike Shop has one Riverbend Cruiser left, and a busy evening ahead. Its checkout must sell the last bike to exactly one shopper, even when two press the button at the same moment; write each order with the price the customer paid; and cancel an order without losing track of the stock. You'll write the five statements behind it in mongosh syntax. Tests run them on Riverbend's data, run two checkouts at once, and run the cancel inside a transaction, then check exactly what changed.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-mongodb-checkout-without-overselling, also linked from the Exercise box beside the lesson. Clone it into your mongodb-course folder. In VS Code, open the mongodb-course folder, open the terminal with Terminal > New Terminal, and type:
git clone https://github.com/ask-codey/exercise-mongodb-checkout-without-overselling.git
Git makes a folder, exercise-mongodb-checkout-without-overselling, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal, and install the packages the tests use:
npm install
The folder holds:
queries.js: the five functions you'll finish.data/: Riverbend's 6 products, 4 orders and 3 customers, andload-into-mongosh.js, which loads them into mongosh so you can try a statement there first.test/: the tests, and the helper that runs your statements for them. You don't need to change either. In this exercise the helper starts a one-member replica set, because transactions need one, and it can run your functions inside a transaction.
What to do
Every function in queries.js gets db, which works like it does in mongosh, and returns db.products.find({}) for now. The comment above each function says exactly what it should do and what it gives back:
/*
* 1. Riverbend has 1 Riverbend Cruiser (_id 1) left. Take 1 from its stock, but only when at least 1 is left.
*
* The first checkout takes it: modifiedCount 1, and the stock goes from 1 to 0.
* A second checkout, even one at the same moment, changes nothing: modifiedCount 0, and the stock stays 0.
*/
export function sellLastCruiser(db) {
return db.products.find({});
}
Replace db.products.find({}) in each function with one mongosh statement of your own, after the word return:
sellLastCruiser: take 1 from the Riverbend Cruiser's stock (_id1), only when at least 1 is left, as above. Its stock starts at 1.sellTwoLights: take 2 from the Beam 400 Light's stock (_id3) in one update, only when at least 2 are left. Its stock starts at 3, so the first sale leaves 1, and a second sale changes nothing.placeOrder: write Leo's new order intoorders:_id1005,customerId8,status"placed",orderedOnISODate("2026-11-17"), and alinesarray with one line:productId4,name"Gravel Runner",priceNumberDecimal("1199.00"),quantity1. It gives back{ acknowledged: true, insertedId: 1005 }.cancelOrder: set Priya's order 1004 tostatus: "canceled", only while its status is still"placed". A second cancel changes nothing, and neither does a cancel of an order that has already shipped.restockCanceled: put the 2 Beam 400 Lights from order 1004 back: add 2 to product 3's stock, so it goes from 3 to 5.
The tests also run cancelOrder and restockCanceled together in one transaction, as the shop's app does, and check that both changes happen. Then they stop a cancel halfway, after cancelOrder and before restockCanceled, and check that the transaction undid it: order 1004 is still "placed" and the stock is still 3. You don't write the transaction: your two statements are its writes.
You can try each statement in mongosh first. In the exercise folder's terminal, start mongosh, type use checkout_practice, then load("data/load-into-mongosh.js") to put Riverbend's data in it. Run the load line again whenever you want the data back as it started. Conditional updates work on any MongoDB server, so you don't need the practice replica set from Transactions, and Why You'll Need Them Less.
Check your work
Run the tests from the exercise folder:
npm test
At first every test fails. That's expected: each statement you finish turns its test green, and tests 6 and 7 turn green once both cancelOrder and restockCanceled work. When a test fails, its message says what it expected and what happened, for example 1) Of two checkouts for the last Riverbend Cruiser, exactly one should take it (modifiedCount 1) and the other change nothing (modifiedCount 0), but their modifiedCounts were 1 and 1. The stock is now -1. That's the race from the lesson, caught by the test.
The tests start their own throwaway MongoDB, so they never change your databases. If you installed MongoDB in Setup: MongoDB, mongosh and Compass, they use it.
Hints
- Put the check in the filter. "Only when at least 1 is left" is a condition on
stock, written beside the_idin the update's filter. Transactions, and Why You'll Need Them Less shows why reading the stock first isn't safe. - Match the check to the amount. Taking 2 needs "at least 2" in the filter, with Comparison Operators: $gt, $lt, $in and More's "greater than or equal to".
- Take away with a negative number. More Update Operators: $inc, $push, $pull and $addToSet shows how
$incadds, and the same operator takes away. - Copy, don't reference, the price. An order line keeps the name and the price paid, as Copying a Few Fields: the Extended Reference Pattern explains; write the price with
NumberDecimal. - "Only while placed" is a second field in the filter. The order's
_idand itsstatusboth have to match.
When you're done
Every test is green, and npm test prints:
✔ 1) sellLastCruiser: two checkouts at once for the last Riverbend Cruiser, and only one gets it (1293.2859ms)
✔ 2) sellTwoLights takes 2 Beam 400 Lights from 3, then changes nothing when only 1 is left (145.6491ms)
✔ 3) placeOrder writes Leo's order 1005 with the Gravel Runner's name and price copied in (138.5774ms)
✔ 4) cancelOrder cancels order 1004 once, changes nothing the second time, and leaves a shipped order alone (142.9583ms)
✔ 5) restockCanceled puts the 2 Beam 400 Lights back: the stock goes from 3 to 5 (135.4572ms)
✔ 6) cancelOrder and restockCanceled in one transaction: both changes happen (134.4103ms)
✔ 7) a cancel that stops halfway is undone: order 1004 stays placed and the stock stays 3 (135.1743ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2607.0802
The times in parentheses will be different on your computer. Now look at your four updates. In each one, which part is the check and which part is the change? What would a shopper see if the app ignored modifiedCount and wrote the order anyway?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here.
On GitHub, click +, then New repository. Name it (for example
exercise-mongodb-checkout-without-overselling), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-mongodb-checkout-without-overselling.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-mongodb-checkout-without-overselling, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
Any checkout works when the shop is quiet. Yours is right when two people want the last bike at the same second, and a cancel that stops halfway leaves nothing out of step.