O
O
Oleksandr Tatarinov2018-07-29 11:18:48
JavaScript
Oleksandr Tatarinov, 2018-07-29 11:18:48

How to sort by different parameters in an API request?

Hey! I want to make it in my online store so that on a single page for the product below there are similar ones, but for this I need to sort the products on the server by parameters (for example, where gender = male and productType = 'T-shirt'). Here is what I was able to write:

router.get('/sort/:sortBy',(req,res,next) => {
  const sort = req.params.sortBy
  Product.find({ gender : req.body.gender})
  .then(response => {
    res.status(200).json(response)
  })
  .catch(err => {
    res.status(500).json({
      error: err
    })
  })
})

sortBy is the name of the parameter to sort by. And how can I make it so that there are several such parameters?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
profesor08, 2018-07-29
@profesor08

Probably like this?

Product.find({ 
  gender : req.body.gender,
  productType: req.body.productType
})

Or maybe it's worth making a post request to the /sort/ page?
Either modify the router to accept parameters like
/sort/:byGenger/:byProductType
But then you will have to remember a clear sequence of parameters, or write a bunch of routers for each option. Both options are bad. Therefore, we went through post.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question