NOTE: I’m not very good at English, but I’ll try to keep things clear.
I am currently learning Express.js and have covered topics like creating routes, middleware, and express-validators—not too much, just at a beginner level to understand how they work.
I know how to use query validators from express-validator
. Initially, I was hardcoding the validation directly in the route, but then I thought of using it as middleware to handle multiple filters. So, I created a function and started using it. The searching and filtering still worked, but my code started to look messy. To improve structure, I moved the query validation logic to a separate file and imported my function from there. That’s when the problem started.
I’ve uploaded the repo to GitHub so you can check it out:
Repo link: Express_Learning
The Issue:
The route is returning an unexpected error that shouldn’t be caused by the filtering logic in my GET /users/search?filterBy=""&value=""
route.
After analyzing my code, I realized that my /users/:id
route might be interpreting filterBy
as :id
. I have a condition in my /users/:id
route that throws an error { msg: "Provide a valid ID" }
if id
is NaN. This error is being thrown when calling /users/search
, even though that route has nothing to do with id
.
I asked ChatGPT, and it suggested that the issue is due to the order of my routes. It recommended placing the /users/search?filterBy=""&value=""
route above the /users/:id
route.
Can someone explain why this happens?