An API Backed by MongoDB

Put it together: keep every database call in one repository module, connect once when the API starts, turn bad ids into 404s, and test the whole API against a real, throwaway MongoDB. Then read Mongoose, the library many Node projects use instead of the driver.

Updated

Database Code in One Place

  1. Keeping Database Code in One Place (Journeyman): A repository module is the one file in an API that talks to MongoDB, with functions such as create and get that give back plain objects whose id is text, so the routes never need to know how the data is stored.
  2. Wiring MongoDB into Express (Journeyman): An Express API connects to MongoDB once when the server starts, hands the database to createApp(db), answers 404 when the repository finds no workout, lets a failed database call reach the error-handling middleware, and closes the connection when Ctrl+C stops it.

Testing with a Real Database

  1. Testing with mongodb-memory-server (Journeyman): mongodb-memory-server starts a real, throwaway MongoDB for a test file, so before starts it, beforeEach gives every test the same fresh data, Supertest tests the whole API against it, and after stops it, with your own data never touched.

Mongoose

  1. Mongoose: Schemas, Models and When Projects Use It (Journeyman): Mongoose is a library built on the MongoDB driver that adds a schema, a model with create, find and findById, and validation before every save, and a project's package.json and model files tell you whether it uses Mongoose or the driver, which is what this course's own code uses.

Exercise: Workout Log API

  1. Exercise: Workout Log API (Journeyman): 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.

Up Next: Users and Security

  1. Up Next: Users and Security (Apprentice): Look back at what Module 3 lets you build, meet the Recipe Box API where you'll show it, and see what Module 4 adds, accounts, signing in and rules about who may do what, so an API knows who is asking.