Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
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?

about 4 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

about 4 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 }));
  }
});
about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!