Personal Catalogue: React, Express & MongoDB — Chapter 5, Exercise 1 ===================================================================== TASK Build both PATCH routes (add and remove) and the TagEditor component, then add and remove several tags on a real Book, confirming after each step via GET /api/items/:id that duplicates are never created and removed tags are genuinely gone. SOLUTION routes/items.js (added after Chapter 3's existing routes): router.patch('/:id/tags/add', async (req, res) => { const { tag } = req.body; if (!tag) return res.status(400).json({ error: 'tag is required' }); const updated = await Book.findByIdAndUpdate( req.params.id, { $addToSet: { tags: tag } }, { new: true, runValidators: true } ).lean(); if (!updated) return res.status(404).json({ error: 'Item not found' }); res.json(updated); }); router.patch('/:id/tags/remove', async (req, res) => { const { tag } = req.body; if (!tag) return res.status(400).json({ error: 'tag is required' }); const updated = await Book.findByIdAndUpdate( req.params.id, { $pull: { tags: tag } }, { new: true } ).lean(); if (!updated) return res.status(404).json({ error: 'Item not found' }); res.json(updated); }); Testing sequence, starting from a real Book with tags: ["Python"]: curl -X PATCH http://localhost:4000/api/items//tags/add \ -H "Content-Type: application/json" -d '{"tag":"Programming"}' curl http://localhost:4000/api/items/ # → tags: ["Python", "Programming"] curl -X PATCH http://localhost:4000/api/items//tags/add \ -H "Content-Type: application/json" -d '{"tag":"Python"}' curl http://localhost:4000/api/items/ # → tags: ["Python", "Programming"] — unchanged, no duplicate added curl -X PATCH http://localhost:4000/api/items//tags/remove \ -H "Content-Type: application/json" -d '{"tag":"Python"}' curl http://localhost:4000/api/items/ # → tags: ["Programming"] — Python is genuinely gone, Programming untouched curl -X PATCH http://localhost:4000/api/items//tags/remove \ -H "Content-Type: application/json" -d '{"tag":"Nonexistent"}' curl http://localhost:4000/api/items/ # → tags: ["Programming"] — removing a tag that was never there is a # harmless no-op, not an error Run with: npx nodemon server.js, then the curl sequence above Output: at each checkpoint, the GET confirms the tags array holds exactly what the sequence of add/remove operations implies -- no duplicates ever appear regardless of how many times the same tag is added, and a removed tag never reappears on a later, unrelated read. WHY THIS WORKS AS AN ANSWER ---------------------------- It builds both routes exactly as the chapter specifies, then verifies their real behavior with an actual sequence of operations against a live database rather than trusting the code to behave correctly -- confirming both the no-duplicate guarantee $addToSet provides and the genuine removal $pull performs, plus the harmless no-op case for removing a tag that isn't present.