0

I wrote a simple mongoose query to sort the DB and display the result, but i wanted to it dynamically so i wrote

exports.sortIt = (req,res,next)=>{
const sortby = JSON.stringify(req.params.sortBy)
var storeArr=[]
dine.find({}).sort({sortby:-1}).then((data)=>{
    console.log(sortby)
    storeArr.push(...data)
    console.log(storeArr.length)
    if(storeArr.length == 0){
        res.status(404).send(storeArr)
    }
    else{
        res.status(200).send(storeArr)
    }
}).catch((err)=>{
    res.status(404).send("error occurred")
})}

Nothing much fancy, however it is not returning the sorted data, it just returns me all of the database, but whenever i hardcode my "sortby" in the query, it returns the correct data.

Can you suggest me what i am doing wrong over ?

My query is correct, there must me something in parsing of "sortBy" from request

Alpit Anand
  • 1,213
  • 3
  • 21
  • 37
  • 3
    What is `dine`? Show where is coming from by the line of code where that actually gets defined. And at least a few lines of code around it for context of where it actually is. – Neil Lunn Mar 23 '19 at 06:50
  • its just a model, and thanks i figured it out, too bad its just moments after posting the question. ti should be [sortby]:1 – Alpit Anand Mar 23 '19 at 06:52
  • 3
    Also note that `storeArr.push(...data)` is a pointless operation here as `data` is already an array. No need to do that. – Neil Lunn Mar 23 '19 at 06:54
  • Sure noted, i did that just to return 404 in case if no data is returned – Alpit Anand Mar 23 '19 at 06:55

0 Answers0