Filter data DB level using Mongoose by passing the options JSON
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); } });}