Personal Catalogue: React, Express & MongoDB — Chapter 6, Exercise 1 ===================================================================== TASK Build the finished /search route (correctly ordered, with escaped input) plus the global error-handling middleware, then confirm a search for an author's name returns the correct Book even when that name never appears in the title, and a search for a nonexistent term returns an empty array rather than an error. SOLUTION routes/items.js (escapeRegex helper plus the search route, registered before GET /:id): function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } router.get('/search', async (req, res) => { const q = (req.query.q || '').trim(); if (!q) return res.status(400).json({ error: 'q is required' }); const regex = new RegExp(escapeRegex(q), 'i'); const items = await Item.find({ $or: [{ title: regex }, { author: regex }, { artist: regex }, { director: regex }], }).lean(); res.json(items); }); // GET /:id (Chapter 3) comes after this in the file, not before server.js (global error-handling middleware, registered last): app.use((err, req, res, next) => { console.error(err); res.status(500).json({ error: 'Server error' }); }); Setup: create a Book with title "Clean Code" and author "Robert C. Martin" (the title itself contains neither "Robert" nor "Martin"). curl -X POST http://localhost:4000/api/items \ -H "Content-Type: application/json" \ -d '{"itemType":"Book","title":"Clean Code","author":"Robert C. Martin"}' Search by author, not title: curl "http://localhost:4000/api/items/search?q=Robert+Martin" Output: [{"_id":"...","title":"Clean Code","itemType":"Book", "author":"Robert C. Martin", ...}] The Book comes back even though "Robert Martin" never appears anywhere in its title -- the $or condition on author is what matched it. Search for something that matches nothing: curl "http://localhost:4000/api/items/search?q=Nonexistent" Output: [] A clean empty array, with a real 200 status -- not a 404 and not an error, since "no results" is a completely normal, valid outcome for a search, not a failure. WHY THIS WORKS AS AN ANSWER ---------------------------- It builds the route exactly as the chapter finalizes it, then proves the cross-field matching genuinely works with a real document whose title alone could never have matched the search term, and confirms the route treats zero results as a normal response rather than an error condition, matching real search UX expectations.