Sort Mongodb data by price
As you probably noticed, the only difference between both codes is the sort()
condition.
Luckily for you, sorting can be done in multiple ways.
IMO the easiest way is to pass a string e.g. price
(ascending) or -price
(descending) via query parameter.
Merge both route handlers into one
app.get('/rentals', function (req, res) { Listings.find({}).sort(req.query.sort).exec(function (err, listings) { if (err) { console.log(err); } else { res.render('rentals', { listings: listings }); } })});
When you sort, call /rentals?sort=price
or /rentals?sort=-price
. This approach also allows you to use other fields e.g. /rentals?sort=anotherField
.