2

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!

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.