The Express unit showed how a request reaches a handler and how JSON is parsed and returned. A handler still has nowhere to keep data that outlives a single request or process. This unit adds a database: MongoDB stores data as documents, and Mongoose, a library for Node.js, adds a schema, validation and a Promise-based query API on top of MongoDB. The examples use ES modules and async/await, which are standard in current Node.js, and assume a Mongoose release in which operations return Promises (callbacks are no longer used for these calls in current Mongoose versions).
1. Documents, collections and the _id
MongoDB does not store rows in fixed tables. A document is a set of field–value pairs, written like a JSON object but stored in a binary encoding (BSON) that has extra types such as dates and object identifiers. Documents are grouped in a collection, and collections live in a database. Two documents in one collection need not have the same fields; MongoDB itself does not require a schema.
Every document has a unique _id field in its collection. If the application does not supply one, a client library generates an ObjectId, a 12-byte value usually shown as 24 hexadecimal characters. In JSON responses an ObjectId appears as a string; it is not a number and not a counter.
A document may contain nested objects and arrays, so one document can hold what a relational design would spread over several tables. For example,
{ "_id": "65a1f0c2e4b0a1b2c3d4e5f6", "title": "Open Day", "venue": "LT1",
"capacity": 200, "tags": ["campus", "visit"] }
is one event with its tags embedded.
2. A Mongoose schema and model
Definition 8.3.1
(Schema, model and document)
A schema declares the fields, types and rules of the documents in one collection. A model is the class compiled from a schema; it reads and writes that collection. A document is one stored record, an instance of the model. The schema lives in the application, so the database enforces only what MongoDB itself enforces, such as a unique index.
Mongoose defines the shape of documents in the application, not in the database. A schema lists fields with their types and rules; a model is a class compiled from a schema that gives access to one collection.
import mongoose from "mongoose";
const eventSchema = new mongoose.Schema(
{
title: { type: String, required: true, trim: true, maxlength: 100 },
venue: { type: String, required: true },
capacity: { type: Number, required: true, min: 1 },
tags: [String],
},
{ timestamps: true }
);
export const Event = mongoose.model("Event", eventSchema);
required, min and maxlength are validators that Mongoose runs before it saves a document. trim is a setter that removes surrounding whitespace. The option timestamps: true adds createdAt and updatedAt. The model named Event uses the collection events: Mongoose lowercases and pluralizes the model name by default. Be aware of the limits of these rules. They are enforced by Mongoose in your Node.js process, so a different program writing to the same collection can bypass them. The option unique: true is different: it asks MongoDB to build a unique index, so uniqueness is enforced by the database, but it is not a validator: a violation is detected only at write time, as an error with code 11000.
Connect once, before serving requests:
await mongoose.connect("mongodb://127.0.0.1:27017/campus");
The path /campus names the database. Keep the connection string out of source files that are committed; read it from the environment.
3. The CRUD operations
All of the following return Promises (or thenable query objects), so each is used with await inside an async function.
Create. Event.create(data) validates, then inserts and returns the new document.
const created = await Event.create({ title: "Open Day", venue: "LT1", capacity: 200 });
Read. Event.find(filter) returns an array of matching documents (empty if none); Event.findById(id) and Event.findOne(filter) return one document or null. A filter is an object of field conditions, with operators such as $gte, $in; a query can be refined with sort, limit and select.
const one = await Event.findById(created._id);
const large = await Event.find({ capacity: { $gte: 100 } }).sort({ capacity: -1 }).limit(10);
const total = await Event.countDocuments({});
Update. findByIdAndUpdate(id, update, options) finds a document, applies update operators such as $set, and returns a document. By default it returns the document as it was before the update, so pass returnDocument: "after". Validators do not run for update queries unless asked, so also pass runValidators: true. If no document matches, the result is null.
const updated = await Event.findByIdAndUpdate(
created._id,
{ $set: { capacity: 250 } },
{ returnDocument: "after", runValidators: true }
);
Delete. deleteOne(filter) removes the first match and returns a result whose deletedCount is 0 or 1.
const result = await Event.deleteOne({ _id: created._id });
4. Where validation runs
Schema rules are not applied uniformly to every operation, so it matters which call reaches the database.
| Operation | Do schema validators run? |
|---|---|
Event.create(data) or new Event(data).save() | Yes, before the write; save() on an existing document checks the paths that were modified |
Event.insertMany(docs) | Yes, for each document |
findByIdAndUpdate, findOneAndUpdate, updateOne | No, unless runValidators: true is passed; then only the paths named in the update are checked |
| A write from another program or the MongoDB shell | Never, because Mongoose is not involved |
Two consequences follow. A route that fetches a document, assigns event.capacity = -5 and calls save() is validated, whereas the same change written as an update query is not, unless runValidators is set. And because validators live in the application, a constraint that must hold for every writer, such as uniqueness, belongs in the database as an index.
Counterexample mode
A schema minimum is not a stored guarantee
Claim: because the schema declares min: 1, no stored event can have a capacity below 1. Create A with capacity 200, which passes validation. Then run await Event.updateOne({ _id: A._id }, { $set: { capacity: 0 } }). The promise resolves normally with modifiedCount 1, since update queries run no schema validators by default, and Event.findById(A._id) now returns capacity 0. A write made from the MongoDB shell would do the same. Passing { runValidators: true }, or loading the document, assigning the field and calling save(), makes Mongoose reject the value; a rule that every writer must obey has to be enforced by the database itself.
5. Connecting CRUD to Express
A route handler must decide what each outcome means in HTTP terms: bad input is a client error, an absent document is a 404, an unexpected exception is a server error. The following two routes use express.json() as in the Express unit.
app.get("/events/:id", async (req, res, next) => {
try {
if (!mongoose.isObjectIdOrHexString(req.params.id)) {
return res.status(400).json({ error: "invalid id" });
}
const event = await Event.findById(req.params.id);
if (!event) return res.status(404).json({ error: "not found" });
res.json(event);
} catch (err) {
next(err);
}
});
app.post("/events", async (req, res, next) => {
try {
const { title, venue, capacity } = req.body;
const event = await Event.create({ title, venue, capacity });
res.status(201).json(event);
} catch (err) {
if (err.name === "ValidationError") {
return res.status(400).json({ error: err.message });
}
next(err);
}
});
Three points matter. First, an invalid id string would make Mongoose throw a CastError; checking with isObjectIdOrHexString first gives a controlled 400 instead of a 500. Second, the handler copies only the three expected fields from req.body into create; passing req.body directly would let a client set fields the route did not intend (mass assignment). Third, the try/catch with next(err) forwards unexpected errors to Express's error handling, and works in both Express 4 and Express 5.
Margin Note
Decide the status code before the code
For each outcome, ask first whether the client should change its request (a 4xx answer) or whether the server failed (5xx). The handler's branches then follow from that list.
6. Worked examples
Worked example 8.3.2
(Tracing a collection through create, query, update and delete)
Start with an empty events collection and let A, B, C be the documents created by the following calls in order.
Event.create({ title: "Open Day", venue: "LT1", capacity: 200 })storesA.Event.create({ title: "Talk", venue: "LT2", capacity: 80 })storesB.Event.create({ title: "Fair", venue: "Hall", capacity: 500 })storesC.Event.create({ title: "Draft", capacity: 10 })throws aValidationErrorbecausevenueis required; nothing is stored. The error'serrorsobject has avenueentry.
Now countDocuments({}) is 3. The query find({ capacity: { $gte: 100 } }).sort({ capacity: -1 }) returns C (500) then A (200); B has capacity 80 and is excluded. After findByIdAndUpdate(A._id, { $set: { capacity: 250 } }, { returnDocument: "after", runValidators: true }), the returned document has capacity 250, and repeating the sorted query returns C (500) then A (250). The call findByIdAndUpdate(B._id, { $set: { capacity: 0 } }, { returnDocument: "after", runValidators: true }) rejects with a ValidationError because 0 is below min: 1, and B remains at 80. Without runValidators: true the same update would silently store 0. Finally deleteOne({ _id: C._id }) gives deletedCount 1, a second identical call gives 0, and countDocuments({}) is 2.
Worked example 8.3.3
(Embedding versus referencing for event reviews)
Two designs can store reviews of an event. Embedding puts them inside the parent document. Referencing stores the parent's id in a separate collection.
// Embedding: the reviews live inside the event document.
const embeddedEventSchema = new mongoose.Schema({
title: String,
reviews: [{ author: String, rating: { type: Number, min: 1, max: 5 } }],
});
// Referencing: each review is its own document that points at an event.
const reviewSchema = new mongoose.Schema({
event: { type: mongoose.Schema.Types.ObjectId, ref: "Event", required: true },
author: String,
rating: { type: Number, min: 1, max: 5 },
});
const Review = mongoose.model("Review", reviewSchema);
const reviews = await Review.find({ event: created._id }).populate("event");
If reviews are always read with the event, are bounded in number and are never queried independently, embedding gives one read and one atomic write for the whole event. If reviews are numerous, grow without bound or are read per user, referencing avoids a document that grows without limit (a MongoDB document has a maximum size of 16 MiB) and allows separate queries. The reference is only an ObjectId: MongoDB does not check that the referenced event exists, so deleting an event can leave reviews that point nowhere unless the application removes them. Mongoose's populate("event") replaces the id by the event document at the cost of a second query. Many-to-many relationships, such as students and courses, use references, because embedding would duplicate data that must stay consistent.
Worked example 8.3.4
(An update route and its five outcomes)
The route below updates the capacity of one event. Assume event A exists with capacity 200 and that express.json() is registered before it.
app.patch("/events/:id", async (req, res, next) => {
try {
if (!mongoose.isObjectIdOrHexString(req.params.id)) {
return res.status(400).json({ error: "invalid id" });
}
if (typeof req.body?.capacity !== "number") {
return res.status(400).json({ error: "capacity must be a number" });
}
const event = await Event.findByIdAndUpdate(
req.params.id,
{ $set: { capacity: req.body.capacity } },
{ returnDocument: "after", runValidators: true }
);
if (!event) return res.status(404).json({ error: "not found" });
res.json(event);
} catch (err) {
if (err.name === "ValidationError") {
return res.status(400).json({ error: err.message });
}
next(err);
}
});
| Request | Path through the handler | Response |
|---|---|---|
PATCH /events/zzz with {"capacity":50} | The id is not an ObjectId or 24-character hexadecimal string | 400 invalid id |
PATCH /events/<id of A> with {"capacity":"many"} | typeof check fails; no database call | 400 capacity must be a number |
PATCH /events/<id of A> with {"capacity":0} | runValidators rejects 0 against min: 1; the catch maps ValidationError | 400 with the validation message |
PATCH /events/<id of A> with {"capacity":250} | Update applied; returnDocument: "after" returns the new document | 200 with capacity 250 |
PATCH /events/<valid id not in the collection> with {"capacity":50} | The query matches nothing and yields null | 404 not found |
The checks run in order of cost and certainty: the id and body shape are checked before any database call, then Mongoose validates the new value, and finally the result of the query decides between 200 and 404. A ValidationError is a client error, so it is mapped to 400; any other exception, such as a lost connection, goes to next(err) and becomes a server error. Without runValidators: true the capacity 0 case would write 0 and return 200, which is the silent failure that the validation section warns about. The two id cases also differ on purpose: a malformed id could never name a document, so the client receives 400, whereas a well-formed id that matches nothing means the resource is absent and receives 404. Keeping them apart tells the client whether to fix its request or to stop looking for the document.
7. Common mistakes
- Forgetting
await: the variable then holds a Promise or a query object, not a document, and the operation may not have completed when the response is sent. - Treating the schema as a database constraint. Mongoose validators run only through Mongoose, and update validators only when
runValidatorsis set. - Passing user-controlled
req.bodyorreq.queryobjects directly as filters or updates; see the web-security unit for operator injection. - Assuming
findByIdAndUpdatereturns the new document withoutreturnDocument: "after". - Sending raw Mongoose errors, which can include internal detail, to clients.
Common mistake
(Comparing ObjectIds with ===)
An ObjectId is an object, so event._id === req.params.id is false even when the string is the same 24 hexadecimal characters: an object and a string are never strictly equal. Two separate ObjectId objects with the same value are also unequal under ===, because it compares identity. Use event._id.equals(otherId), or compare String(event._id) with String(otherId).
Common mistake
(Treating unique as a validator)
Declaring unique: true asks MongoDB to build a unique index; it adds no validator. If two events with the same title already exist, building the index fails and the duplicates stay. When a later create repeats a value, the driver reports a duplicate-key error with code 11000, not a ValidationError, so the POST route above would pass it to next(err) and answer 500. Test err.code === 11000 and answer with a client error, commonly 409.
8. Practice
Quick check
(Write a schema)
Write a Mongoose schema for a student with a required name of at most 50 characters, an integer study year between 1 and 4, and an email that is unique. State which of these rules is enforced by the database.
Solution
const studentSchema = new mongoose.Schema({
name: { type: String, required: true, maxlength: 50 },
year: { type: Number, min: 1, max: 4,
validate: { validator: Number.isInteger, message: "year must be an integer" } },
email: { type: String, required: true, unique: true },
});
required, maxlength, min, max and the custom validator are enforced by Mongoose before saving. Only unique: true asks MongoDB to create a unique index, so only the uniqueness of email is enforced by the database, as a duplicate-key error (code 11000) when a second document with the same email is written.
Quick check
(Delete and sort)
The collection events contains A (capacity 200), B (capacity 80) and C (capacity 500). After deleteOne({ capacity: { $lt: 100 } }) and then find({}).sort({ capacity: 1 }), which documents are returned, in which order, and what was deletedCount?
Solution
The filter matches only B (80), so B is deleted and deletedCount is 1. The remaining documents sorted by ascending capacity are A (200) then C (500).
Quick check
(The stale response)
A route runs await Event.findByIdAndUpdate(id, { capacity: 0 }) and the response shows the event with its old capacity, yet the database now holds 0. Explain and correct the call.
Solution
By default findByIdAndUpdate returns the document as it was before the update, so the response shows the old capacity. Validators also do not run on updates by default, so the schema rule min: 1 did not reject 0. The corrected call is await Event.findByIdAndUpdate(id, { $set: { capacity: 0 } }, { returnDocument: "after", runValidators: true }), which now rejects with a ValidationError for capacity 0; with a valid capacity such as 120 it returns the updated document.
Quick check
(Embed or reference)
A Student has a list of at most 5 hobby strings and belongs to exactly one Program shared by hundreds of students. Choose embedding or referencing for each relationship and justify it.
Solution
Hobbies: embed as an array of strings. The list is small and bounded, belongs to the student and is read with the student. Program: reference it, by storing the program's ObjectId in the student document. Many students share one program, so embedding would copy the program's data into hundreds of documents and any change would have to be repeated in each; with a reference there is one program document to update.
Quick check
(Save versus update)
A route runs const event = await Event.findById(id); event.capacity = -5; await event.save();. Does the rule min: 1 apply? What would Event.updateOne({ _id: id }, { capacity: -5 }) do by comparison?
Solution
Yes. save() validates the modified path capacity, so the call rejects with a ValidationError and the stored document is unchanged. The updateOne call runs no schema validators by default and writes -5 silently. Passing { runValidators: true } as its options makes it validate the updated path and reject, the same as the update in the worked example.