# Exercise: Product Catalog Rules

Write five mongosh statements for Riverbend Bike Shop's catalog, an order with copied names and prices, a review that keeps the five newest and the numbers behind the average, two searches across bikes, helmets and lights, and the rules that keep bad products out, and let the tests check each one.

Journeyman · MongoDB · Updated November 19, 2026

By Gregor Dzierzon

Riverbend Bike Shop's catalog holds bikes, helmets and lights in one `products` collection, and the shop's app needs five things from it: an order that remembers what the customer paid, a review that keeps the product page small, a cheap-helmets list, a size M search, and rules that keep a bad product out. Each one is a pattern or a rule from this chapter, and you'll write each as one statement in mongosh syntax. Tests run your statements on the same 8 products as this chapter's lessons and check exactly what each one finds or leaves behind.

## Get the exercise code

Open this lesson's GitHub repository, [github.com/ask-codey/exercise-mongodb-product-catalog-rules](https://github.com/ask-codey/exercise-mongodb-product-catalog-rules), 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:

```bash
git clone https://github.com/ask-codey/exercise-mongodb-product-catalog-rules.git
```

Git makes a folder, `exercise-mongodb-product-catalog-rules`, with the exercise code inside. Open that folder in VS Code (**File > Open Folder**), open its terminal, and install the packages the tests use:

```bash
npm install
```

The folder holds:

- `queries.js`: the five functions you'll finish.
- `data/products.json`: Riverbend's 8 products, the same ones you loaded from `riverbend-catalog.js` in *Copying a Few Fields: the Extended Reference Pattern*.
- `data/load-into-mongosh.js`: loads those products 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.

## 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 the result is:

```javascript
/*
 * 3. Find the helmets that cost less than 60, cheapest first.
 *
 *    Finds 2 products, in this order: Junior Helmet (39), then Harbor Helmet (59). Some lights cost less than 60
 *    too, and they must not be in the list.
 */
export function cheapHelmets(db) {
  return db.products.find({});
}
```

Replace `db.products.find({})` in each function with one mongosh statement of your own, after the word `return`:

1. **`placeOrder`**: insert Alex's order into `db.orders` with the extended reference pattern: `_id` 5006, `customerId` 1, `customerName` `"Alex"`, and two `items`. The first is `{ productId: 104, name: "Summit Helmet", price: 89, quantity: 1 }`; write the second the same way for product 106, the Beacon Rear Light, with a quantity of 2 and its name and price copied from `data/products.json`.
2. **`addReview`**: in one `updateOne` on the Riverbend Road 2 (`_id` 101), put Jonah's review `{ by: "Jonah", stars: 5, text: "Best climb of my summer.", date: ISODate("2026-11-15") }` first in `reviews`, keep only the first five, and add 1 to `reviewCount` and 5 to `starsTotal`. Afterward the count is 13, the total 59, and the reviews are by Jonah, Ana, Omar, Grace and Dev.
3. **`cheapHelmets`**: the 2 helmets that cost less than 60, cheapest first, as above.
4. **`sizeMedium`**: the 4 products that come in size M: the 2 bikes whose `frameSizes` include `"M"` and the 2 helmets whose `headSizes` include `"M"`.
5. **`addProductRules`**: give `products` its rules with `db.runCommand({ collMod: "products", validator: { ... } })`. Every product must have a `name` that is text, a `type` of `"bike"`, `"helmet"` or `"light"`, and a `price` that is a number of 0 or more; a bike must also have `frameSizes`.

For task 5, the tests let in three good products: a bike with `frameSizes`, a helmet with no `frameSizes`, and a light with a price of 0. They expect *Document failed validation* for six bad ones: no name, a name that is a number (29), the type `"scooter"`, a price of -5, a price written as text (`"49"`), and a bike with no `frameSizes`. For example, `{ _id: 20, type: "helmet", name: "Trail Helmet", price: 69, headSizes: ["M"] }` goes in, and `{ _id: 21, type: "scooter", name: "Trail Scooter", price: 149 }` is refused.

You can try each statement in mongosh first. In the exercise folder's terminal, start `mongosh`, type `use catalog_rules` to choose a practice database, then `load("data/load-into-mongosh.js")` to put the 8 products in it. When a statement does the right thing there, copy it into its function after `return`. Loading the file again puts the products back as they were, rules removed.

## Check your work

Run the tests from the exercise folder:

```bash
npm test
```

At first every test fails. That's expected: each statement you finish turns its tests green. When a test fails, its message says what it expected and what your statement did, for example *2) After addReview, the Road 2's reviews should be by Jonah, Ana, Omar, Grace and Dev, in that order: Jonah's first and Lena's gone. They are by Ana, Omar, Grace, Dev, Lena.* Task 2 has two tests: one runs your update once, the other three times, to check the reviews never grow past five. Task 5 has seven: one for the three good products, and one for each bad one.

The tests start their own throwaway MongoDB, so they never change your databases, and they load the products fresh, with no rules, before every test. 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

- **Copy, don't look up later.** Task 1's point is that the order keeps the customer's name and each product's name and price paid. *Copying a Few Fields: the Extended Reference Pattern* shows an order like it.
- **`$push` needs three helpers for "newest five".** `$each` (a list, even for one review), `$position: 0` and `$slice: 5`, then `$inc` beside `$push` in the same update. *Keeping Documents Small: the Subset and Computed Patterns* shows the whole update.
- **Watch the lights.** Some lights cost less than 60, so "helmets" has to be in the filter. "Cheapest first" is a sort, from *Sorting and Paging: sort, limit and skip*.
- **Size M is two different fields.** A bike's size is in `frameSizes` and a helmet's in `headSizes`. *Different Shapes in One Collection: the Polymorphic Pattern* asks the same kind of question.
- **The bike rule is "either, or".** "If it's a bike, it needs frameSizes" means "either it isn't a bike, or it has frameSizes". *Schema Validation with $jsonSchema* shows a validator with exactly that beside its `$jsonSchema`.

## When you're done

Every test is green, and `npm test` prints:

```text
✔ 1) placeOrder saves order 5006 with Alex's name and each item's name and price copied (1147.4099ms)
✔ 2) addReview puts Jonah's review first, keeps five reviews, and adds 1 to reviewCount and 5 to starsTotal (11.9623ms)
✔ 3) addReview, run three times, still keeps five reviews, and the average is 69 / 15 = 4.6 (12.4714ms)
✔ 4) cheapHelmets finds Junior Helmet, then Harbor Helmet (11.7789ms)
✔ 5) sizeMedium finds the 2 bikes and 2 helmets that come in size M (10.5273ms)
✔ 6) addProductRules gives products a validator that lets in a bike with frameSizes, a helmet with no frameSizes and a light with a price of 0 (11.4374ms)
✔ 7) addProductRules refuses a product with no name (10.2364ms)
✔ 8) addProductRules refuses a name that is a number (9.6274ms)
✔ 9) addProductRules refuses the type "scooter" (9.8974ms)
✔ 10) addProductRules refuses a price of -5 (9.6229ms)
✔ 11) addProductRules refuses a price written as text (10.4441ms)
✔ 12) addProductRules refuses a bike with no frameSizes (8.8733ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1692.4315
```

The times in parentheses will be different on your computer. Now look back at your five statements. If Riverbend raised the Summit Helmet's price tomorrow, which of your statements would still say 89, and why is that right? If the shop started selling scooters, which line of your rules would change?

## 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.

1. On GitHub, click **+**, then **New repository**. Name it (for example `exercise-mongodb-product-catalog-rules`), choose **Public**, and click **Create repository**. Leave out the README: your folder already has one.
2. 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:

   ```bash
   git remote set-url origin https://github.com/your-name/exercise-mongodb-product-catalog-rules.git
   git add .
   git commit -m "My solution"
   git push -u origin main
   ```

3. Paste your repo's address, such as `https://github.com/your-name/exercise-mongodb-product-catalog-rules`, 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

An order that remembers what was paid, a product page that stays small, searches across different kinds of product, and a collection that turns bad data away: that's a store's data model doing its job, and you wrote every piece of it.

## Key terms

- [Extended Reference Pattern](https://www.ask-codey.com/glossary/extended-reference-pattern)
- [Subset Pattern](https://www.ask-codey.com/glossary/subset-pattern)
- [Computed Pattern](https://www.ask-codey.com/glossary/computed-pattern)
- [Polymorphic Pattern](https://www.ask-codey.com/glossary/polymorphic-pattern)
- [Schema Validation](https://www.ask-codey.com/glossary/schema-validation)

## Related

- [Copying a Few Fields: the Extended Reference Pattern](https://www.ask-codey.com/lessons/mongodb-extended-reference-pattern)
- [Keeping Documents Small: the Subset and Computed Patterns](https://www.ask-codey.com/lessons/mongodb-subset-and-computed-patterns)
- [Different Shapes in One Collection: the Polymorphic Pattern](https://www.ask-codey.com/lessons/mongodb-polymorphic-pattern)
- [Schema Validation with $jsonSchema](https://www.ask-codey.com/lessons/mongodb-schema-validation)

Source: https://www.ask-codey.com/lessons/exercise-mongodb-product-catalog-rules
