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?
CodePudding user response:
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
CodePudding user response:
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 }));
}
});