• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

131
Views
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) =>{
    FILM
        .find().limit(6)
        .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?

almost 3 years ago · Santiago Trujillo
2 answers
Answer question

0

Try this:

router.get('/', (req, res) =>{
    var sortFilter = { rating : 1 };
    FILM.find().sort(sortFilter).limit(6)
        .then(films => res.render('index.ejs', {films}))
})

Please refer docs for more information

almost 3 years ago · Santiago Trujillo Report

0

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) {
    FILM.find()
      .sort({ rating: 1 })
      .limit(6)
      .then((films) => res.render("index.ejs", { films }));
  } else {
    FILM.find()
      .limit(6)
      .then((films) => res.render("index.ejs", { films }));
  }
});
almost 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error