Exercise: Adoption Applications with Mongoose
Write a Mongoose schema and model for the Maple Street Pet Adoption Center's adoption applications, with required fields, an allowed list of statuses and a reference to the pet, then the three data-layer functions its API calls, and let the tests check each one.
Journeyman · MongoDB · Node.js · Updated
People who want to adopt one of the Maple Street Pet Adoption Center's pets fill in an application on its website, and the staff approve or decline each one. The API's routes are written and handed to you. Your work is the data underneath, in Mongoose: a schema and model for an application, and the three functions the routes call to save one, list a pet's applications, and change an application's status. Tests run your code against a throwaway MongoDB and check every rule.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-mongodb-adoption-applications-with-mongoose, 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-adoption-applications-with-mongoose.git
Git makes a folder, exercise-mongodb-adoption-applications-with-mongoose, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal, and install the packages it uses, Mongoose 9.12.2 and Express among them:
npm install
The folder holds:
models/application.js: the Application model, with an empty schema for you to fill in. The comment at the top lists its five fields.data/applications.js: the three functions the routes call, for you to finish. Each one stops with Not built yet. for now.models/pet.js: the Pet model, the same as in Mongoose: What It Adds and What It Hides. Ready to use.app.js: the API's three routes, which call your functions and answer 201, 200, 400 or 404. Ready to use.server.js,.env.exampleandapplications.http: run the API against your own MongoDB and try its requests. Ready to use.test/: the tests, the shelter's four pets and three applications they start with, and the helper that starts a throwaway MongoDB. You don't need to change any of it.
What to do
1. The schema, in models/application.js. An application has five fields:
| Field | Holds | Rules |
|---|---|---|
pet |
the _id of the pet it's for |
an ObjectId that refers to the Pet model; required |
applicant |
the applicant's name, such as "Rosa" |
text; required |
email |
their email address, such as "rosa@example.com" |
text; required |
status |
where the application stands | text; only "submitted", "approved" or "declined"; "submitted" when none is given |
message |
a note from the applicant | text; optional |
2. The data layer, in data/applications.js. The comment above each function says exactly what it gives back:
addApplication(details)saves a new application and gives back the saved one. Saving{ pet: Mochi's id, applicant: "Rosa", email: "rosa@example.com" }gives back Rosa's application with an_idand status"submitted". A missing field or a status that isn't allowed is refused by the model with a ValidationError: let it go, and the route answers 400.listApplicationsForPet(petId)gives back every application for one pet, as plain objects, each with the pet's name and species filled in. For Mochi, that's Rosa's and Theo's applications, in any order, each withpet: { _id: ..., name: "Mochi", species: "cat" }. For Clover, who has none, it's an empty list.setStatus(id, status)changes one application's status and gives back the changed application.setStatuswith Theo's application's id and"approved"gives back Theo's application with status"approved". With an id no application has, it gives backnull(the route answers 404). With a status that isn't allowed, such as"maybe", the model refuses it with a ValidationError and the stored application keeps its status (the route answers 400).
Check your work
Run the tests from the exercise folder:
npm test
At first all 11 tests fail. That's expected: tests 1 to 4 check your schema, and tests 5 to 11 send requests to the API, so each part you finish turns its tests green. When a test fails, its message says what it expected and what happened, for example 3) An application with status "maybe" should be refused, but it was saved. Allow only "submitted", "approved" and "declined" with enum.
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. If you didn't, the first npm test downloads MongoDB for the tests (about 950 MB on Windows, about 180 MB on a Mac) and keeps it for every exercise after this one.
To try the API by hand, copy .env.example to .env, run npm start, and send the requests in applications.http with VS Code's REST Client extension. If your maple_street database has no pets yet, the first start adds four of them, Mochi among them.
Hints
- Start with the schema. Tests 1 to 4 check it on its own, and the functions are short once it's right. Mongoose: What It Adds and What It Hides shows
required,enum,defaultand a field withref. - A reference is an ObjectId with
ref. Its type ismongoose.Schema.Types.ObjectId, andref: "Pet"names the model it points to. - Don't catch the ValidationError in
addApplication. The route catches it and answers 400; a function that catches it and carries on hides the problem. - "Filled in" means
populate, and "plain objects" meanslean(). Both chain ontofind, in either order. - Watch the update that skips the rules. Test 10 sends the status
"maybe".updateOneandfindByIdAndUpdatedon't check the schema unless you ask; finding the application, setting its status and callingsave()always does. AndfindByIdgives backnullwhen no application has the id.
When you're done
Every test is green, and npm test prints:
✔ 1) the Application model saves Rosa's application for Biscuit with status submitted (1162.31ms)
✔ 2) an application with no pet, applicant or email is refused with a ValidationError naming all three (23.0138ms)
✔ 3) an application with status maybe is refused with a ValidationError on status (20.0581ms)
✔ 4) pet refers to the Pet model, so populate fills in Biscuit's name for Imani's application (22.7557ms)
✔ 5) POST /applications with Rosa's application for Biscuit answers 201 with status submitted (38.2861ms)
✔ 6) POST /applications with no email answers 400 (21.508ms)
✔ 7) GET /pets/<Mochi's id>/applications answers Rosa's and Theo's applications, each with pet name Mochi and species cat (22.5197ms)
✔ 8) GET /pets/<Clover's id>/applications answers an empty list (18.4363ms)
✔ 9) PATCH /applications/<Theo's id>/status with approved answers 200 with status approved, and stores approved (22.9175ms)
✔ 10) PATCH /applications/<Theo's id>/status with maybe answers 400 and leaves Theo's application submitted (20.5434ms)
✔ 11) PATCH /applications/<an id with no application>/status answers 404 (18.3297ms)
ℹ tests 11
ℹ suites 0
ℹ pass 11
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2034.7313
The times in parentheses will be different on your computer. Now look at your schema the way someone using mongosh would: which of its rules would stop them from saving status: "maybe" straight into the collection, and what would you add to the database so that one did?
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-adoption-applications-with-mongoose), 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-adoption-applications-with-mongoose.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-adoption-applications-with-mongoose, 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 schema, a model and three small functions are a whole data layer for one kind of document, and you know both what Mongoose checked for you and what it would have let slip.