CRUD Endpoints & Validation
By the end of this lesson the TaskBoard API will support all four CRUD actions (Create, Read, Update, Delete) on tasks. You will add PATCH and DELETE routes, check every request body and query string with Zod before it reaches the database, and test each route with curl, including the requests that should fail.
What you should know first: MongoDB & Mongoose Models, because this lesson changes the controller and routes you wrote there. Zod itself is taught in Validating Input, and Mongoose updates in Update Documents. Versions checked: Express 5.3.0, Mongoose 9.12.1 and Zod 4.6.7. Every output below comes from a real run of this code.
The complete contract
Build a REST API with Express 5 promised two more routes. Here is the finished table for tasks:
| Method and path | Meaning | Success reply |
|---|---|---|
GET /api/tasks | List tasks; optional status, assignee, limit | 200 with an array |
GET /api/tasks/:id | One task | 200 with an object |
POST /api/tasks | Create a task | 201, the task and a Location header |
PATCH /api/tasks/:id | Change some fields | 200 with the updated task |
DELETE /api/tasks/:id | Remove a task | 204 with no body |
PATCH means "change only the fields I send". PUT means "replace the whole thing with what I send", so a PUT without dueDate should clear the due date. A task board mostly changes one field at a time, such as dragging a card from "Doing" to "Done", so TaskBoard uses PATCH.
204 No Content means "done, nothing to show". DELETE is idempotent: sending it twice leaves the database in the same state as sending it once. The second call simply gets 404, because the task is already gone.
Why validate twice?
Think of a railway reservation. The booking clerk checks your form at the counter: name filled, valid train number, date in the future. Later the TTE checks your ticket on the train. The clerk catches most mistakes early and politely; the TTE is the last line of defence.
TaskBoard has the same two layers:
- Zod at the door. A validation schema describes what a valid request looks like. A middleware checks it before any controller runs, collects every problem at once, and strips fields the client is not allowed to send.
- Mongoose at the database. The schema from the last lesson still checks types,
maxlengthandenumon every save. If a future route forgets the Zod step, bad data still cannot get in.
Install Zod into the server workspace from the top folder:
npm install zod -w serverStep 1: Describe valid input
Create server/src/validation/tasks.validation.js. Each field is described once and reused by the create, update and list schemas:
// Rules for what clients may send to /api/tasks. Checked before any controller runs.
import { z } from "zod";
import { TASK_STATUSES } from "../models/index.js";
const objectId = z.string().regex(/^[0-9a-f]{24}$/i, "assignee must be a 24-character user id");
const taskFields = {
title: z.string("Title is required").trim().min(1, "Title is required").max(120, "Title must be 120 characters or fewer"),
status: z.enum(TASK_STATUSES, `status must be one of: ${TASK_STATUSES.join(", ")}`),
dueDate: z.iso.date("dueDate must be a date like 2026-11-25").nullable(),
assignee: objectId.nullable(),
};
// POST: title is required; new tasks always start as "todo".
export const createTaskSchema = z.object({
title: taskFields.title,
dueDate: taskFields.dueDate.optional(),
assignee: taskFields.assignee.optional(),
});
// PATCH: every field is optional, but at least one must be sent.
export const updateTaskSchema = z
.object(taskFields)
.partial()
.refine((data) => Object.keys(data).length > 0, "Send at least one field to change");
// GET /api/tasks?status=todo&assignee=...&limit=20
export const listTasksQuery = z.object({
status: taskFields.status.optional(),
assignee: objectId.optional(),
limit: z.coerce.number("limit must be a number").int().min(1, "limit must be 1-100").max(100, "limit must be 1-100").default(50),
});A few details matter here. z.object() strips keys it does not list, so a client that sends "status": "done" to POST gets a normal todo task, exactly as before. .nullable() lets a PATCH send "dueDate": null to clear a date or "assignee": null to unassign. .partial() makes every field optional. Query strings always arrive as text, so z.coerce.number() turns "20" into 20, and .default(50) means a list never returns thousands of tasks at once.
Step 2: One middleware for every route
Create server/src/middleware/validate.js. It turns Zod's problems into the same details array that Mongoose errors already use, so the React client handles both the same way:
// Checks req.body or req.query against a Zod schema and replies 400 with details on failure.
function toDetails(error) {
return error.issues.map((issue) => ({
field: issue.path.join(".") || "body",
message: issue.message,
}));
}
export function validateBody(schema) {
return (req, res, next) => {
const result = schema.safeParse(req.body ?? {});
if (!result.success) {
return res.status(400).json({ error: { message: "Validation failed", details: toDetails(result.error) } });
}
req.body = result.data;
next();
};
}
export function validateQuery(schema) {
return (req, res, next) => {
const result = schema.safeParse(req.query);
if (!result.success) {
return res.status(400).json({ error: { message: "Validation failed", details: toDetails(result.error) } });
}
res.locals.query = result.data;
next();
};
}safeParse never throws; it returns either success: true with clean data, or the list of issues. On success, req.body is replaced by the cleaned data, so controllers only ever see trimmed, checked fields.
Why res.locals.query instead of req.query? In Express 5, req.query is a getter: a property computed each time you read it. Assigning to it does not stick, so the cleaned query (with limit as a number) goes in res.locals, the object Express provides for data that belongs to one request.
Step 3: Routes, with one id check
Replace server/src/routes/tasks.routes.js:
import { Router } from "express";
import mongoose from "mongoose";
import { listTasks, getTask, createTask, updateTask, deleteTask } from "../controllers/tasks.controller.js";
import { validateBody, validateQuery } from "../middleware/validate.js";
import { createTaskSchema, updateTaskSchema, listTasksQuery } from "../validation/tasks.validation.js";
export const tasksRouter = Router();
// Runs before every route with :id. A malformed id can never match a task.
tasksRouter.param("id", (req, res, next, id) => {
if (!mongoose.isObjectIdOrHexString(id)) {
return res.status(404).json({ error: { message: "Task not found" } });
}
next();
});
tasksRouter.get("/", validateQuery(listTasksQuery), listTasks);
tasksRouter.get("/:id", getTask);
tasksRouter.post("/", validateBody(createTaskSchema), createTask);
tasksRouter.patch("/:id", validateBody(updateTaskSchema), updateTask);
tasksRouter.delete("/:id", deleteTask);router.param("id", ...) runs once for any route in this router that has :id. The ObjectId check that used to live inside getTask now protects GET, PATCH and DELETE together. Each route line reads like a sentence: "for PATCH on an id, validate the body, then update".
Step 4: The controller
Replace server/src/controllers/tasks.controller.js:
import { Task, User } from "../models/index.js";
const notFound = { error: { message: "Task not found" } };
// Returns an error reply body if the assignee id does not belong to a real user.
async function checkAssignee(assignee) {
if (!assignee) return null;
if (await User.exists({ _id: assignee })) return null;
return { error: { message: "Validation failed", details: [{ field: "assignee", message: "No user with this id" }] } };
}
export async function listTasks(req, res) {
const { status, assignee, limit } = res.locals.query;
const filter = {};
if (status) filter.status = status;
if (assignee) filter.assignee = assignee;
const tasks = await Task.find(filter).sort({ dueDate: 1 }).limit(limit).populate("assignee", "name");
res.json(tasks);
}
export async function getTask(req, res) {
const task = await Task.findById(req.params.id).populate("assignee", "name");
if (!task) return res.status(404).json(notFound);
res.json(task);
}
export async function createTask(req, res) {
const problem = await checkAssignee(req.body.assignee);
if (problem) return res.status(400).json(problem);
const task = await Task.create(req.body);
await task.populate("assignee", "name");
res.status(201).location(`/api/tasks/${task.id}`).json(task);
}
export async function updateTask(req, res) {
const problem = await checkAssignee(req.body.assignee);
if (problem) return res.status(400).json(problem);
const task = await Task.findById(req.params.id);
if (!task) return res.status(404).json(notFound);
task.set(req.body);
await task.save();
await task.populate("assignee", "name");
res.json(task);
}
export async function deleteTask(req, res) {
const task = await Task.findByIdAndDelete(req.params.id);
if (!task) return res.status(404).json(notFound);
res.status(204).end();
}Passing req.body to Task.create() is safe now, because Zod has already removed every field that is not in the schema. Zod can check that assignee looks like an id, but only the database knows whether that user exists, so checkAssignee asks with User.exists(), which fetches only the _id.
updateTask uses load, change, save: findById, then task.set(), then task.save(). Saving runs every Mongoose validator and updates updatedAt. The one-query alternative is Task.findByIdAndUpdate(id, changes, { returnDocument: "after", runValidators: true }). Without runValidators: true, Mongoose skips schema validators on updates. In Authentication with JWT & Cookies the loaded task also lets us check who is allowed to change it.
Step 5: Try every route
Start the API with npm run dev and move a task to "done" (your ids will differ):
curl -s -i -X PATCH http://localhost:4000/api/tasks/6afa99020e80bfa64f4766fa -H "Content-Type: application/json" -d "{\"status\":\"done\"}"HTTP/1.1 200 OK
{"title":"Call parents about Sunday test","status":"done","dueDate":"2026-11-18T00:00:00.000Z","assignee":{"name":"Kabir Malik","id":"6afa99020e80bfa64f4766f8"},"createdAt":"2026-11-16T05:47:46.961Z","updatedAt":"2026-11-16T05:47:52.763Z","id":"6afa99020e80bfa64f4766fa"}Only status and updatedAt changed. Now the requests that should fail. Each line shows the request, then the status and body that came back:
PATCH {"status":"finished","title":"","dueDate":"next Friday"}
400 {"error":{"message":"Validation failed","details":[{"field":"title","message":"Title is required"},{"field":"status","message":"status must be one of: todo, doing, done"},{"field":"dueDate","message":"dueDate must be a date like 2026-11-25"}]}}
PATCH {}
400 {"error":{"message":"Validation failed","details":[{"field":"body","message":"Send at least one field to change"}]}}
PATCH {"assignee":"6afa8c70c0a73c0001de0000"}
400 {"error":{"message":"Validation failed","details":[{"field":"assignee","message":"No user with this id"}]}}
GET /api/tasks?status=late&limit=500
400 {"error":{"message":"Validation failed","details":[{"field":"status","message":"status must be one of: todo, doing, done"},{"field":"limit","message":"limit must be 1-100"}]}}
GET /api/tasks/abc
404 {"error":{"message":"Task not found"}}Notice that the first request reports all three problems at once. A form can then mark every wrong field in one go instead of making the user fix them one by one. Creating a task while sending a forbidden field shows the stripping:
POST {"title":"Book hall for parent meeting","dueDate":"2026-11-25","status":"done"}
201 Location: /api/tasks/6afa990b7611274309b593b1
{"title":"Book hall for parent meeting","status":"todo","dueDate":"2026-11-25T00:00:00.000Z","assignee":null,"createdAt":"2026-11-16T05:47:55.711Z","updatedAt":"2026-11-16T05:47:55.711Z","id":"6afa990b7611274309b593b1"}Finally, delete that task. Run the same command twice:
curl -s -i -X DELETE http://localhost:4000/api/tasks/6afa990b7611274309b593b1HTTP/1.1 204 No Content
HTTP/1.1 404 Not Found
{"error":{"message":"Task not found"}}The operator trick from the last lesson is still closed. ?status[$ne]=done arrives as a key literally named status[$ne], which listTasksQuery does not list, so Zod strips it and the request returns the normal unfiltered list.
Send only what changed
A PATCH body should contain only the fields the user really edited. The example below compares a saved task with the form's current values, builds the PATCH body, and runs the same rules as updateTaskSchema, so the user sees problems before anything is sent. The server still checks again.
import { useState } from "react";
import { createRoot } from "react-dom/client";
const saved = { id: "6afa99020e80bfa64f4766fa", title: "Call parents about Sunday test", status: "doing", dueDate: "2026-11-18" };
// Same rules as updateTaskSchema on the server.
function check(changes) {
const problems = [];
if (Object.keys(changes).length === 0) problems.push("body: Send at least one field to change");
if ("title" in changes && !changes.title.trim()) problems.push("title: Title is required");
if ("title" in changes && changes.title.trim().length > 120) problems.push("title: Title must be 120 characters or fewer");
return problems;
}
function changedFields(before, after) {
return Object.fromEntries(Object.entries(after).filter(([key, value]) => before[key] !== value));
}
function EditTask() {
const [draft, setDraft] = useState({ title: saved.title, status: saved.status, dueDate: saved.dueDate });
const changes = changedFields(saved, { ...draft, dueDate: draft.dueDate || null });
const problems = check(changes);
const edit = (field) => (e) => setDraft({ ...draft, [field]: e.target.value });
return (
<div>
<p><label>Title <input value={draft.title} onChange={edit("title")} size="35" /></label></p>
<p>
<label>Status <select value={draft.status} onChange={edit("status")}>
<option>todo</option><option>doing</option><option>done</option>
</select></label>{" "}
<label>Due <input type="date" value={draft.dueDate} onChange={edit("dueDate")} /></label>
</p>
<p><code>PATCH /api/tasks/{saved.id}</code></p>
<pre>{JSON.stringify(changes, null, 2)}</pre>
{problems.length > 0
? <ul style={{ color: "crimson" }}>{problems.map((p) => <li key={p}>{p}</li>)}</ul>
: <p style={{ color: "green" }}>Ready to send.</p>}
</div>
);
}
createRoot(document.getElementById("root")).render(<EditTask />);At first the body is {} and the page shows "body: Send at least one field to change". Pick done and the body becomes { "status": "done" }. Clear the date and "dueDate": null appears, which is how the client asks the server to remove a due date. Empty the title and the title rule fires.
Common mistakes
Task.findByIdAndUpdate(id, req.body)with the raw body. The client can then set any field, and validators do not run. Validate first, and addrunValidators: trueif you use update queries.- Assigning to
req.queryin Express 5. The change is lost; keep cleaned query values inres.locals. - Returning
200with{ "deleted": true }from DELETE. Use204with no body; the status code already says it worked. - Trusting an id because it has the right shape. A valid-looking ObjectId can still point to a user who does not exist. Check with
User.exists(). - No upper limit on lists. One request for every task in the database is slow and easy to abuse. Cap
limit.
Interview questions
1. What is the difference between PUT and PATCH?
PUT replaces the whole resource with the request body, so missing fields are cleared or reset. PATCH changes only the fields that are sent. PATCH suits small changes such as moving a task between columns, and it avoids overwriting fields another user changed meanwhile.
2. Why validate with Zod if Mongoose already has a schema?
Zod checks the request at the edge, before any database work, and can validate things Mongoose never sees, such as query strings and "send at least one field". It also strips unknown fields and reports every problem at once. Mongoose remains the last guard on every save, so the two layers protect each other.
3. Is DELETE idempotent if the second call returns 404?
Yes. Idempotency is about the state on the server, not the response. After one or many identical DELETE calls the task is gone either way. The different status codes simply report what each call found.
4. Why does findByIdAndUpdate need runValidators: true?
Mongoose runs schema validators automatically on save() and create(), but not on update queries. Without the option, an update could store an invalid status or an over-long title. Load-change-save avoids the problem because save() always validates.
Key points
- TaskBoard now has full CRUD:
PATCHreturns the updated task with200,DELETEreturns204. - Zod schemas in
validation/tasks.validation.jscheck bodies and query strings;validateBodyandvalidateQueryrun them before controllers. z.object()strips unknown fields,.partial()makes PATCH fields optional,z.coerce.number()converts query text.- In Express 5,
req.querycannot be reassigned; keep cleaned values inres.locals.query. router.param("id", ...)checks the id once for every:idroute.- Validation errors from Zod and Mongoose share one shape:
{ "error": { "message", "details" } }.
Exercise
Add a dueBefore filter to GET /api/tasks, so that ?dueBefore=2026-11-19 returns only tasks due before 19 November. Reject anything that is not a YYYY-MM-DD date with a 400 that names the field. Test it with a good date and with ?dueBefore=tomorrow.
Show solution
// validation/tasks.validation.js, inside listTasksQuery
dueBefore: z.iso.date("dueBefore must be a date like 2026-11-20").optional(),
// controllers/tasks.controller.js, in listTasks
const { status, assignee, dueBefore, limit } = res.locals.query;
// ...
if (dueBefore) filter.dueDate = { $lt: new Date(dueBefore) };GET /api/tasks?dueBefore=2026-11-19 200, two tasks:
Update physics batch timings | 2026-11-12
Call parents about Sunday test | 2026-11-18
GET /api/tasks?dueBefore=tomorrow
400 {"error":{"message":"Validation failed","details":[{"field":"dueBefore","message":"dueBefore must be a date like 2026-11-20"}]}}The filter is built from a value Zod has already checked, so the client never controls the $lt operator. new Date("2026-11-19") is midnight UTC, the same way the due dates are stored.
Quick Quiz
1. Which reply should DELETE /api/tasks/:id send when the task was removed?
204 No Content says the action worked and there is nothing more to send.
2. A client sends {"title":"Order chalk","status":"done"} to POST /api/tasks. What happens?
createTaskSchema does not list status, and z.object() removes unlisted keys.
3. Why does validateQuery store the result in res.locals.query?
res.locals holds data for the current request and is never sent automatically.
4. What does PATCH /api/tasks/:id with body {} return?
The .refine() on updateTaskSchema rejects an empty change.
Learn MERN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
