Exercise: Farmers Market Vendors

Write the Saturday Farmers Market's vendor functions with the official driver (filters with $in and $gte, a sorted page with its total, one vendor by its id, updates with $set and $push, a delete, two indexes and a text search) and let tests on a throwaway MongoDB check every one.

Journeyman · MongoDB · NoSQL · Node.js · Updated

By

The Saturday Farmers Market's app has a list of questions for its database: who sells honey, which organic vendors shoppers rate best, the vendor list five at a time, one vendor by its id, and a search box. The market's manager has changes, too: move a vendor to a new stall, add a product, remove a vendor who has left. You'll write each one as a small function, and tests check every function as you go, on a throwaway MongoDB of their own.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-farmers-market-vendors, also linked from the Exercise box beside the lesson. Clone it into your nodejs-course folder. In VS Code's terminal:

cd ~/nodejs-course
git clone https://github.com/ask-codey/exercise-node-farmers-market-vendors.git

Git makes a folder, exercise-node-farmers-market-vendors, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and install the packages:

npm install

Then copy .env.example to a new file named .env, which holds the connection string npm start uses: Copy-Item .env.example .env in PowerShell, or cp .env.example .env on a Mac. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder.

The folder holds:

  • vendors.js: the nine functions, for you to finish.
  • vendors.json: the market's 12 vendors, the same ones as in this chapter's lessons.
  • show-vendors.js: runs your functions against your own MongoDB and prints what each one gave back.
  • vendors.test.js: the tests. You don't need to change it.
  • throwaway-database.js: starts the throwaway MongoDB the tests use. You don't need to read it or change it.

What to do

Each function in vendors.js stops with the error Not built yet. for now. Each one is given vendors, the collection, and the comment at the file's top says what each one takes and gives back:

//   vendorsSelling(vendors, products)    the names of the vendors who sell any of the products in the list, A to Z:
//                                        ["honey", "jam"] gives ["Bee Happy Honey", "Berry Patch", "Maple Grove Syrup"]
//   topOrganic(vendors)                  the organic vendors rated 4 or more, highest rating first, each as
//                                        { name, rating } and nothing else: 6 vendors, { name: "Berry Patch",
//                                        rating: 4.8 } first and { name: "Herb Corner", rating: 4 } last
//   vendorPage(vendors, page, pageSize)  one page of all the vendors, sorted by stall, as
//                                        { page, pages, total, vendors }, with each vendor as { name, stall } and
//                                        nothing else: vendorPage(vendors, 2, 5) gives page 2, pages 3, total 12
//                                        and the vendors at stalls 6 to 10
//   findVendor(vendors, id)              the vendor whose _id is the text id, as the whole document; null when id
//                                        isn't a valid ObjectId, or when no vendor has it
//   moveVendor(vendors, name, stall)     moves the vendor with that name to the new stall, and gives back the whole
//                                        vendor as it is after the move; null when no vendor has that name
//   addProduct(vendors, name, product)   adds the product to the end of that vendor's products and gives back true;
//                                        false when no vendor has that name
//   removeVendor(vendors, name)          removes the vendor with that name and gives back true; false when no vendor
//                                        has that name
//   createIndexes(vendors)               makes two indexes: a unique index on stall, so no two vendors can share a
//                                        stall, and a text index on name and products
//   searchVendors(vendors, words)        the names of the vendors whose name or products hold any of the words, A to Z,
//                                        with a $text search: "honey" gives ["Bee Happy Honey", "Maple Grove Syrup"].
//                                        It needs the text index, so call createIndexes first.
  1. Find with filters. Finish vendorsSelling and topOrganic: a filter, a sort, and for topOrganic a projection.
  2. Page through the vendors. Finish vendorPage: the total, the number of pages, and one sorted page.
  3. Find one by its id. Finish findVendor, which checks the text before it makes an ObjectId.
  4. Change and remove. Finish moveVendor, addProduct and removeVendor, each answering whether the vendor was there.
  5. Index and search. Finish createIndexes, then searchVendors.

Check your work

Run the tests from the exercise folder:

npm test

No MongoDB needs to be running: the tests start a throwaway MongoDB of their own, and before every test they save the 12 vendors fresh, so one test's changes never reach another and your own data is never touched. If MongoDB is installed on your computer, the tests use it. If it isn't, the first npm test downloads MongoDB for the tests, about 950 MB on Windows and about 180 MB on a Mac, once per computer, and keeps it for every exercise after this one.

At first all 21 tests fail. That's expected: each function you finish turns its tests green. A failing test's message says what it expected and what came back, for example No vendor is named Herb Korner, so addProduct should give back false, but it gave back true. Which count says whether a vendor matched?

To see your functions work on your own MongoDB, run npm start with your server running. It starts the market database's vendors over each time, so run it as often as you like.

Hints

  • Let MongoDB do the work. A filter, a sort and a projection, as in Finding Documents with Filters, beat reading every vendor and sorting them in JavaScript. $in matches any value in a list, even on an array field such as products.
  • A page is three numbers and a list. Sorting and Paging Results works out the skip from the page number, counts with countDocuments, and rounds the pages up with Math.ceil. Page 4 of 3 is an empty list, not an error.
  • Check the id first. ObjectId.isValid(id), then new ObjectId(id), as findVendor does in Finding Documents with Filters.
  • Pick the call by the answer you need. Updating and Deleting Documents: findOneAndUpdate with returnDocument: "after" gives back the vendor, updateOne's matchedCount says whether one was found, and deleteOne's deletedCount says whether one went.
  • Two indexes, two calls. Indexes and Text Search makes a unique index with { unique: true } and a text index on several fields at once. $text with $search does the rest.

When you're done

Every test is green, and npm start prints what each of your functions gave back:

Saved 12 vendors, with the indexes.
Selling honey or jam: Bee Happy Honey, Berry Patch, Maple Grove Syrup
Organic and rated 4 or more: Berry Patch 4.8, Sunny Acres 4.7, Pumpkin Patch 4.5, Green Valley Greens 4.2, Fungi Friends 4.1, Herb Corner 4
Page 2 of 3 (12 vendors): 6 Herb Corner, 7 Orchard Lane, 8 Maple Grove Syrup, 9 Bee Happy Honey, 10 Fungi Friends
Found by its id: Sunny Acres
Found by the id stall-4: null
Moved Herb Corner to stall 13.
Added thyme to Herb Corner: true
Removed Petal & Stem: true (11 vendors left)
Searching for tomato: Sunny Acres
Searching for honey cheese: Bee Happy Honey, Hilltop Dairy, Maple Grove Syrup

Now look back at moveVendor. What happens if the manager moves Herb Corner to stall 4, Sunny Acres's stall, after createIndexes has run? What should an API answer the manager when that happens?

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. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-node-farmers-market-vendors), 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:

    git remote set-url origin https://github.com/your-name/exercise-node-farmers-market-vendors.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-node-farmers-market-vendors, 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

Every endpoint of an API backed by MongoDB ends in one of these nine functions: a filter, a page, one document by its id, a change or a delete. In the next chapter, routes call functions like them, and their null and false answers become 404s.

Key terms

Related