Exercise: Workout Log API

Move Rep Counter's in-memory workouts API onto MongoDB by writing a repository module and wiring it into the routes with createApp(db), with 404s for bad and missing ids, and let Supertest tests on a throwaway MongoDB check every request.

Journeyman · Node.js · MongoDB · REST API · Updated

By

Rep Counter's members log every workout, and every time the server restarts, the log is empty again: the API keeps its workouts in an array. You'll move it onto MongoDB, the way this chapter did one route at a time: a repository module that holds every database call, routes that call the repository, and a 404 for any id that isn't a workout. Tests check every request on a throwaway MongoDB of their own.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-workout-log-api, 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-workout-log-api.git

Git makes a folder, exercise-node-workout-log-api, 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:

  • workoutsRepository.js: the repository's five functions, for you to finish.
  • app.js: createApp(db), for you to finish with the routes.
  • inMemoryApp.js: the API as it was, with its workouts in an array. Read it; you'll move its routes into app.js.
  • server.js: connects to your MongoDB and starts the API at http://localhost:3100.
  • workouts.http: the requests to try with REST Client.
  • app.test.js: the tests. You don't need to change it.
  • throwaway-database.js: starts the throwaway MongoDB the tests use. Testing with mongodb-memory-server explains it.

What to do

For now, every function in workoutsRepository.js stops with the error Not built yet., and app.js answers every request with a 404 that says the same. The comment at the top of workoutsRepository.js says what each function gives back:

//   create(workout)      saves { member, date, sets } and gives back the workout with its new id
//   list({ from, to })   the workouts dated from `from` to `to`, both days included, oldest date first.
//                        Either one can be left out (undefined), and with neither it's every workout.
//   get(id)              the workout with that id, or null when there's none, or when id isn't an id at all
//   addSet(id, set)      adds the set, { exercise, reps, weight }, to the end of the workout's sets and gives back
//                        the changed workout, or null when there's no such workout
//   remove(id)           deletes the workout and gives back true, or false when there was no such workout

Every workout they give back is a plain object, { id, member, date, sets }, with its id as text and no _id. The comment at the top of app.js lists every request and its answer:

//   GET    /workouts                                  200, every workout, oldest date first
//   GET    /workouts?from=2026-11-10&to=2026-11-16    200, the workouts dated from the 10th to the 16th, both included
//   GET    /workouts?from=2026-11-12                  200, the workouts dated the 12th or later
//   GET    /workouts?to=2026-11-12                    200, the workouts dated the 12th or earlier
//   GET    /workouts/:id                              200, that workout
//   POST   /workouts                                  201, the new workout with its id; the body is { member, date, sets }
//   POST   /workouts/:id/sets                         201, the workout with the new set at the end of its sets;
//                                                     the body is { exercise, reps, weight }
//   DELETE /workouts/:id                              204, no body
//
// An id with no workout, or one that isn't an id at all, such as /workouts/not-an-id, answers
//   404, { "status": 404, "title": "Not Found", "detail": "There's no workout not-an-id." }
// on GET /workouts/:id, POST /workouts/:id/sets and DELETE /workouts/:id alike.
  1. Write the repository. Finish the five functions in workoutsRepository.js, each with the driver call that does its job.
  2. Build the app around it. In app.js, make the repository from db inside createApp(db), then move each route from inMemoryApp.js into it, swapping each use of the array for a call to the repository.
  3. Turn "no such workout" into a 404. When the repository gives back null or false, answer 404 with sendProblem, which comes over from inMemoryApp.js along with the error-handling middleware.

Check your work

Run the tests from the exercise folder:

npm test

No server and no MongoDB of your own need to be running: the tests start a throwaway MongoDB, put the same three workouts in it before every test (Dana's on November 9, Luis's on November 12 and Dana's on November 16), and send each request to createApp with Supertest. At first all 15 tests fail. That's expected: each part you finish turns its tests green. A failing test's message says what it sent and what came back, for example GET /workouts should answer 200, but it answered 404 with {"message":"Not built yet."}.

To try the API yourself, start it with npm start (MongoDB must be running on your computer, or .env must hold an Atlas connection string), open workouts.http, and click Send Request above each request. Stop it with Ctrl+C.

Hints

  • One function at a time. Tests 1 to 3 call the repository directly, so you can finish get and list and see them pass before you touch app.js.
  • Plain objects out. Keeping Database Code in One Place writes create, get and the toWorkout helper that turns _id into id. Every function that gives back a workout needs that helper.
  • A filter you build piece by piece. For list, start with an empty object and add $gte for from and $lte for to only when each is there. The dates are text such as "2026-11-16", which sorts in date order. Finding Documents with Filters and Sorting and Paging Results have the operators and sort.
  • Change, then give back the new version. findOneAndUpdate with $push and returnDocument: "after", from Updating and Deleting Documents, adds the set and gives back the changed workout in one call, or null when nothing matched. deleteOne tells you how many it deleted.
  • Check the id first. ObjectId.isValid(id) before new ObjectId(id), in every function that takes an id, or not-an-id turns into a 500.

When you're done

Every test is green, and with npm start running, workouts.http's requests get answers like these (each request, then its answer's status line and body; your ids will be different):

POST /workouts
HTTP/1.1 201 Created
{"id":"6afc998e106e58a87b8a6c2b","member":"Dana","date":"2026-11-16","sets":[{"exercise":"squat","reps":8,"weight":135}]}

GET /workouts?from=2026-11-10&to=2026-11-16
HTTP/1.1 200 OK
[{"id":"6afc998e106e58a87b8a6c2c","member":"Luis","date":"2026-11-12","sets":[{"exercise":"bench press","reps":10,"weight":95}]},{"id":"6afc998e106e58a87b8a6c2b","member":"Dana","date":"2026-11-16","sets":[{"exercise":"squat","reps":8,"weight":135}]}]

POST /workouts/6afc998e106e58a87b8a6c2b/sets
HTTP/1.1 201 Created
{"id":"6afc998e106e58a87b8a6c2b","member":"Dana","date":"2026-11-16","sets":[{"exercise":"squat","reps":8,"weight":135},{"exercise":"squat","reps":6,"weight":155}]}

GET /workouts/not-an-id
HTTP/1.1 404 Not Found
{"status":404,"title":"Not Found","detail":"There's no workout not-an-id."}

DELETE /workouts/6afc998e106e58a87b8a6c2b
HTTP/1.1 204 No Content

Stop the server, start it again, and send GET /workouts: the workouts are still there. Now look at your routes. How many of them mention ObjectId or collection? If the gym moved its workouts to another database, which file 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. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-node-workout-log-api), 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-workout-log-api.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-workout-log-api, 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 repository behind every route, one client for the whole API and tests on a real throwaway database: that's how the APIs you'll build from here on keep their data, users and passwords included.

Key terms

Related