Home > Software engineering >  Express api with conditions in query params
Express api with conditions in query params

Time:04-10

I am working on express Api with mongoose to create get Api for my project. I was able to make one get call successfully. But I am not sure how to make api for sorting data by different fields enter image description here

Model

id,
productName,
costPrice,
soldPrice

router.get("/sellProduct",
(req, res, next) => {
    // condition
    if(req.query.product){
      Product.find({prodName:req.query.product} ).then(data => {
        if (data) {
          res.status(200).send(data)
        }
      })
    }
// WHAT SHOULD BE THE SORT LOGIC TO SORT BY DIFF FIELD
    else if(req.query.sortBy){
      Product.find({}).sort().then(data => {
        if (data) {
          res.status(200).send(data)
        }
      })
    }

    
    else{
      Product.find().then(data => {
        if (data) {
          res.status(200).send(data)
        }
      })
    }
 });

I am beigneer and trying my best but any help will be appreciated

CodePudding user response:

You can build the parameters for .find and .sort dynamically:

router.get("/sellProduct", (req, res, next) => {
  const findParams = {};
  const sortParams = {
    lowerCostPrice:  { costPrice:  1 },
    higherCostPrice: { costPrice: -1 },
    lowerSoldPrice:  { soldPrice:  1 },
    higherSoldPrice: { soldPrice: -1 },
    /* add more sort options ... */
  }[req.query.sortBy];
  
  if (req.query.product) findParams.prodName = req.query.product
  /* add more search options ... */

  Product.find(findParams).sort(sortParams).then(data => {
    if (data) {
      res.status(200).send(data);
    } else {
      res.status(404);
    }
  }).catch(err => {
    console.log(err);
    res.status(500);
  });
});

CodePudding user response:

If I understand you question correctly, you can add a switch block and depending on the passed value, sort the products:

router.get('/sellProduct', (req, res, next) => {
  let result;
  // ...
  if (req.query.sortBy) {
    switch (req.query.sortBy) {
      case 'lowerCostPrice': {
        result = await Product.find({}).sort({ price: 'asc' });
        break;
      }
      case 'higherCostPrice': {
        result = await Product.find({}).sort({ price: 'desc' });
        break;
      }
      // and so on...
    }
  }
  // ...
  res.status(200).send(result);
});
  • Related