How to send a sorted result from my MongoDB database by clicking on a button?


I have this code where i send my collection to index.ejs

router.get('/', (req, res) =>{
        .then(films => res.render('index.ejs', {films}))

In index.ejs I want to sort my collection by rating from button.
What way can I do it?


You can add in index.ejs an anchor tag that would send a request to / with a url param, something like this for example:

<a href="/?sort=1">Sort</a>

You change you request handler, so that when there is a query parameter, it send a sorted list, otherwise send a normal one.

router.get("/", (req, res) => {
  const sort = req.query.sort;
  if (sort) {
      .sort({ rating: 1 })
      .then((films) => res.render("index.ejs", { films }));
  } else {
      .then((films) => res.render("index.ejs", { films }));

Answered By – yousoumar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published