Filter data DB level using Mongoose by passing the options JSON

Viewed 545

I am trying to filter an array of objects which has a set of products objects.I want to filter the data on basis of name in ascending or descending order.Have written some code but it is not showing any filtering effect on the result object.

Using NodeJS with Mongoose!

filter_data(req, res) {
  const sort = {}

  if (req.body.sortBy && req.body.OrderBy) {
    sort[req.body.sortBy] = req.body.OrderBy === 'desc' ? -1 : 1
  }

  ProductModel.find({}, {}, {
    options: sort
  }, (err, ProductModel1) => {
    if (err) {
      console.log(err);
      res.status(500).json({
        "err": err
      });
    } else {
      console.log(ProductModel1);
      if (ProductModel1 == null) {
        res.status(404).json({
          "msg": "Product list is empty"
        });
      } else
        res.status(200).json(ProductModel1);
    }
  });
}

1 Answers

There is no need to put the options parameter for filtering in the query. We can directly give sort and limit and that filters the data dynamically using the parameters sent!

filter_data(req, res) {
  const sort = {}

  if (req.body.sortBy && req.body.OrderBy) 
  {
    sort[req.body.sortBy] = req.body.OrderBy === 'desc' ? -1 : 1
  }

  console.log(sort)


  ProductModel.find({}, null, {sort: sort,limit: 2}, (err, ProductModel1) =>{            
    if (err) {
      console.log(err);
      res.status(500).json({
        "err": err
      });
    } else {
      console.log(ProductModel1);
      if (ProductModel1 == null) {
        res.status(404).json({"msg": "Product list is empty"});
      } else
        res.status(200).json(ProductModel1);
    }
  });
}

Related