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
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
2
Answers
You can build the parameters for
.find
and.sort
dynamically:If I understand you question correctly, you can add a switch block and depending on the passed value, sort the products: