# A Data Layer

A Data Layer: A Data Layer: One File That Talks to the Database, When the Database Says No: Bad ids, Duplicates and Not Found, Testing the Data Layer with…

Updated: November 19, 2026

1. [A Data Layer: One File That Talks to the Database](https://www.ask-codey.com/lessons/mongodb-driver-a-data-layer) (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.
2. [When the Database Says No: Bad ids, Duplicates and Not Found](https://www.ask-codey.com/lessons/mongodb-driver-when-the-database-says-no) (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.
3. [Testing the Data Layer with mongodb-memory-server](https://www.ask-codey.com/lessons/mongodb-driver-testing-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.

Source: https://www.ask-codey.com/courses/mongodb-in-depth/topics/mongodb-data-layer
