1

Goal: I'm trying to find a way to let a user sort rentals by max and min price on the one index page.

My problem is the only way I could figure out how to make it work was to create two separate pages specifically for lowprice and highprice. I want to only have one main index.

The pricelow page shown below filters the data from low to high prices

        app.get("/pricelow", function(req, res){
        Listings.find({}).sort({price: 1}).exec(function(err, allListings){
               if(err){
                   console.log(err);
               } else {
               res.render("pricelow",{listings:allListings});
               }
          })
    });

//The pricehigh page shown below filters the data from high to low prices

app.get("/pricehigh", function(req, res){
    Listings.find({}).sort({price: -1}).exec(function(err, allListings){
               if(err){
                   console.log(err);
               } else {
               res.render("pricehigh",{listings:allListings});
               }
          })
    });
AndrewLeonardi
  • 3,351
  • 9
  • 47
  • 100

1 Answers1

3

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.

Mikey
  • 6,728
  • 4
  • 22
  • 45