Reputation: 35
Usually, when I have to make a GET request using NodeJS and MongoDB, I do a separate search for every field.
For Example:
localhost:3000/movie/:name/:author - GET
As I would expect to get a movie, desired name, and author, everything will be working fine.
But what if I want to make a request query like this:
localhost:3000/movies/filters[‘movies’]=USA&fields=id,name,author - GET
Is that possible in NodeJS and MongoDB using the SAME query?
How can it be done?
Thanks so much!
Upvotes: 2
Views: 10176
Reputation: 7734
Yes, it is possible.
In the first route you're using request parameters. In the second route you're trying to use request queries on the route: /movies
. (Query strings are not part of the route path)
But you're slightly off, in express, you can do a GET request with string queries like this:
localhost:3000/movies?filters[movies]=USA&fields[]=id&fields[]=name
^ ^ ^ ^
1 2 3 4
?
Indicates start of query string=
Separates key from its value&
Separates each key=value pair[]
To treat key as an arrayThen you can access the values in the router by using the req.query
property:
router.get('/movies', (req, res) => {
console.log(req.query.filters.movies); // => USA
console.log(req.query.fields); // => [ 'id', 'name' ]
});
To learn more, I suggest you read the official Express routing guide.
Upvotes: 1