Exercise: Ratings and Favorites
Write seven mongosh changes behind Sunday Kitchen's buttons, from rating a recipe and counting its saves to saving a meal plan with an upsert and deleting old plans, and let the tests check every document afterward.
Apprentice · MongoDB · Updated
Sunday Kitchen's website has buttons now: a star rating, a Save button, a heart for favorites, a weekly meal planner, and a tidy-up for the menu. Behind each button is one change to the database, and you'll write all seven in mongosh syntax. Tests run your changes on Sunday Kitchen's recipes, cooks and meal plans, then read back every document to check that what should change did, and that nothing else did.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-mongodb-ratings-and-favorites, 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-ratings-and-favorites.git
Git makes a folder, exercise-mongodb-ratings-and-favorites, 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 seven functions you'll finish.data/recipes.json: Sunday Kitchen's 40 recipes, the same ones you loaded in Adding Many Documents with insertMany.data/cooks.json: three cooks, Maya, Leo and Priya, and their favorite recipes.data/mealPlans.json: five weekly meal plans, one document per cook per week.data/load-into-mongosh.js: loads all three into mongosh, so you can try a change there first.test/: the tests, and the helper that runs your changes for them. You don't need to change either.
What to do
Every function in queries.js gets db, which works like it does in mongosh, and returns a find({}) for now, which only reads. The comment above each function says exactly what it should change, and what the documents look like afterward:
/*
* 1. Veggie Stir-Fry (_id 13) has no rating yet. Give it a rating of 4.4.
*
* Afterward, Veggie Stir-Fry has rating: 4.4, and every other field of it, and every other recipe, is unchanged.
*/
export function rateRecipe(db) {
return db.recipes.find({});
}
Replace the find({}) statement in each function with one mongosh statement of your own, after the word return:
rateRecipe: give Veggie Stir-Fry (_id13) a rating of 4.4, as above.countSave: add 1 to Chickpea Curry's (_id4)saves. It has nosavesfield yet. The test runs your function twice, so Chickpea Curry ends withsaves: 2.addFavorite: add"Pad Thai"to Maya's favorites (the cook with_id1) only if it isn't there yet. The test runs it twice, so her favorites end as["Chickpea Curry", "Black Bean Tacos", "Pad Thai"].removeFavorite: take"Lemon Bars"out of Leo's favorites (the cook with_id2). His list holds it twice, and both copies go, leaving["Weeknight Chili"]. Priya's Lemon Bars stay.saveMealPlan: savemonday: "Chickpea Curry"in Maya's plan for week 48 (cook: "Maya", week: 48), whether or not that plan exists yet. It doesn't yet, so the first save makes{ cook: "Maya", week: 48, monday: "Chickpea Curry" }with an_idMongoDB makes. The test runs it twice, and there must still be exactly one plan for Maya's week 48.archiveLowRated: soft-delete the 2 recipes rated below 3.8, Minestrone (3.7) and Overnight Oats (3.6), by settingarchived: trueon them. Caesar Salad, rated exactly 3.8, and the 7 recipes nobody has rated yet stay as they are.deleteOldPlans: delete Leo's meal plans from before week 40: his weeks 38 and 39. His week 47 plan and both of Maya's plans stay.
You can try each change in mongosh first. In the exercise folder's terminal, start mongosh, type use ratings_and_favorites to choose a practice database, then load("data/load-into-mongosh.js") to put the data in it. Try a change, read the documents back with find, and when it does exactly what the comment says, copy it into its function after return. Loading the file again puts the data back as it started.
Check your work
Run the tests from the exercise folder:
npm test
At first every test fails. That's expected: each change you finish turns its test green. When a test fails, its message says what it expected and which documents are different, for example 3) addFavorite should add "Pad Thai" to Maya's favorites only if it isn't there. It ran twice, so her favorites should be [ "Chickpea Curry", "Black Bean Tacos", "Pad Thai" ]., followed by Maya's document as your change left it.
The tests start their own throwaway MongoDB and load the data fresh before each test, so they never change your databases. If you installed MongoDB in Setup: MongoDB, mongosh and Compass, they use it. If you didn't, the first npm test downloads MongoDB for the tests, nearly 1 GB on Windows and about 180 MB on a Mac, which can take a few minutes; it's kept for every exercise after this one.
Hints
- Name the change first. "Add 1" is
$inc, "only if it isn't there" is$addToSet, "every copy out of a list" is$pull, and "whether or not it exists yet" is an upsert. More Update Operators: $inc, $push, $pull and $addToSet and Upserts and Replacing a Whole Document have each one. - One document or many?
updateOnechanges the first match, andupdateManyevery match. Tasks 1 to 5 change one document; task 6 changes two. - Look before you change. Run each filter with
findin mongosh first. Deleting Documents Safely shows why a filter with$notwould archive the seven unrated recipes too. - Delete with both conditions. Task 7 is Leo's plans and before week 40. Two fields in one filter already mean "and".
- Run it twice. Tasks 2, 3 and 5 are tested twice. Try yours twice in mongosh and read the documents: is the result still what the comment says?
When you're done
Every test is green, and npm test prints:
✔ 1) rateRecipe gives Veggie Stir-Fry (_id 13) a rating of 4.4 (1045.5977ms)
✔ 2) countSave, run twice, leaves Chickpea Curry (_id 4) with saves: 2 (24.2397ms)
✔ 3) addFavorite, run twice, adds Pad Thai to Maya's favorites once (24.3609ms)
✔ 4) removeFavorite takes both Lemon Bars out of Leo's favorites, leaving Weeknight Chili (23.2902ms)
✔ 5) saveMealPlan, run twice, leaves exactly one plan for Maya's week 48 with monday: Chickpea Curry (23.2334ms)
✔ 6) archiveLowRated sets archived: true on Minestrone and Overnight Oats, the 2 recipes rated below 3.8 (24.0459ms)
✔ 7) deleteOldPlans deletes Leo's week 38 and week 39 plans, and keeps the other 3 (22.4444ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1549.2986
The times in parentheses will be different on your computer. Now look at task 2 again: what would Chickpea Curry's saves be if two cooks tapped Save at the same moment and your app had used $set with a number it read first? And for task 6, how would Sunday Kitchen's menu query leave out the archived recipes?
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-ratings-and-favorites), 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-ratings-and-favorites.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-ratings-and-favorites, 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
A star rating, a save count, a favorites list, a planner and a tidy-up: each is one change you can now write, check with find first, and trust to leave everything else alone. That's what most buttons in an app do to a database.