Personal Catalogue: React, Express & MongoDB — Chapter 6, Exercise 2 ===================================================================== TASK Temporarily move the /search route to after GET /:id, reproducing the route-ordering bug -- confirm a real CastError-triggered response for a search request. Restore the correct order and confirm the fix. SOLUTION Temporarily reorder routes/items.js so /search comes last: router.get('/', ...); router.get('/:id', ...); // now registered BEFORE /search router.put('/:id', ...); router.delete('/:id', ...); router.patch('/:id/tags/add', ...); router.patch('/:id/tags/remove', ...); router.get('/search', ...); // moved to the end Send a real search request: curl -i "http://localhost:4000/api/items/search?q=kurosawa" Output (with the bug reproduced): HTTP/1.1 500 Internal Server Error Content-Type: text/html; charset=utf-8
CastError: Cast to ObjectId failed for value "search" (type string) at path "_id" for model "Item" ...A real HTML error page, not the JSON this API returns everywhere else. The server's own console log (from the global error-handling middleware's console.error(err)) confirms exactly what happened: Item.findById() was called with "search" as the id, because /:id matched the request before /search ever got a chance to. Now restore the correct order: router.get('/', ...); router.get('/search', ...); // moved back before /:id router.get('/:id', ...); router.put('/:id', ...); router.delete('/:id', ...); router.patch('/:id/tags/add', ...); router.patch('/:id/tags/remove', ...); Repeat the identical request: curl -i "http://localhost:4000/api/items/search?q=kurosawa" Output (fixed): HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 [{"_id":"...","title":"Seven Samurai","director":"Akira Kurosawa", ...}] The real Dvd, matched correctly by director. WHY THIS WORKS AS AN ANSWER ---------------------------- It reproduces the exact ordering bug the chapter describes with a real request and a real observed CastError response, confirms the failure is genuinely about route registration order (not the search route's own logic, which never changed), and shows the identical request succeeding once the two routes are reordered -- proving cause and fix with real, before-and-after evidence rather than asserting the explanation.