The Official Node.js Driver
Swap the starter's in-memory list for MongoDB. Connect with the official driver, turn the mongosh queries you know into driver calls, keep them in one data layer, answer the database's errors with the right status code, and test it all against a throwaway database.
Updated
Driver Basics
- Connecting from Node: MongoClient and the Connection String (Journeyman): The official mongodb package connects a Node app to MongoDB through a MongoClient made from a connection string, which lives in a .env file that Node reads with --env-file, and the app connects that one client when it starts and closes it when it stops.
- From mongosh to the Driver: find, insertOne and toArray (Journeyman): Every mongosh query has a twin in the Node.js driver, written with db.collection("pets"), await, a projection inside an options object, toArray() to read a cursor, and new ObjectId(id) imported from the driver, and insertOne gives back the new document's insertedId.
A Data Layer
- A Data Layer: One File That Talks to the Database (Journeyman): A data layer keeps every driver call in one file, data/pets.js, whose functions listPets, getPet, addPet and updatePet the routes call without ever touching the driver, turning each document into a plain pet and building filters, a projection, a sort and pages from the query string.
- When the Database Says No: Bad ids, Duplicates and Not Found (Journeyman): An API answers each way a request can fail with the status that says whose problem it is, so a text that isn't an ObjectId gets 400, an id with no pet 404, a duplicate key (code 11000) 409, a document the validator refuses (code 121) 400, and a database that's down 500 with the details logged and never sent.
- Testing the Data Layer with mongodb-memory-server (Journeyman): mongodb-memory-server starts a real, throwaway MongoDB for a test file, the way the helper in every exercise of this course does, so before starts it, beforeEach puts the same documents back for every test, node --test and assert check the data layer, Supertest checks a route, and after stops it, never touching your own data.
Exercise: Pet Listings Data Layer
- Exercise: Pet Listings Data Layer (Journeyman): Move the Maple Street Pet Adoption Center's API from an array to MongoDB by finishing its data layer with the official driver, from the paged and filtered list to the right status for a bad id and a missing pet and the indexes the list needs, and let the tests check every request on a throwaway MongoDB.