goldendawn07
goldendawn07

Reputation: 35

How to create a query string filtering the search by specific parameters?

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

Answers (1)

u-ways
u-ways

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
  1. ? Indicates start of query string
  2. = Separates key from its value
  3. & Separates each key=value pair
  4. [] To treat key as an array

Then 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

Related Questions