Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
Express api with conditions in query params

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

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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);
  });
});
over 4 years ago · Santiago Trujillo Denunciar

0

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);
});
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda