在查询参数中使用条件表达 api

Express api with conditions in query params

我正在使用 mongoose 开发 express Api 来为我的项目创建 get Api。我能够成功拨打电话。但是我不确定如何使 api 用于按不同字段对数据进行排序

型号

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)
        }
      })
    }
 });

我很努力,我会尽力而为,但我们将不胜感激

您可以动态构建 .find.sort 的参数:

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);
  });
});

如果我理解你的问题正确,你可以添加一个开关块并根据传递的值对产品进行排序:

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);
});