Search code examples
javascriptnode.jsmongodbexpressmongoose

Model.find().sort() returning an empty array


let query = Tour.find(JSON.parse(queryStr));


if (req.query.sort) {
  query = query.sort(req.query.sort);//a string 'ratings'
}


const tours = await query;

res.status(200).json({
  status: 'success',
  requestedAt: req.requestTime,
  result: tours.length,
  data: {
    tours,
  },
});

this is my code here tours should return me all the data but it's just giving me a empty array. I'm new to all of this and i can't find a solution but i know for sure something is happening in the sort method I'm using cause i used the debugger and i can't understand what's happening inside there.

I'm using mongoose v5 and node is v18 i don't know if that's the problem so if someone can help me out it would be great


Solution

  • Too long to be a comment. When debugging this, try hardcoding the feature first and then adding dynamic values.

    I just tried recreating what you have and it works fine, so the problem is probably in your value for queryStr or req.query.sort. Below is my test setup

    // Model
    const Tour = mongoose.model('tours', new mongoose.Schema({
        ratings: Number,
        description: String,
    }))
    
    // Initial data
    // const tour1 = await Tour.create({ ratings: 8, desc: "Bad" })
    // const tour2 = await Tour.create({ ratings: 3, desc: "Bad" })
    // const tour3 = await Tour.create({ ratings: 1, desc: "Cool" })
    // const tour4 = await Tour.create({ ratings: 4, desc: "Bad" })
    // const tour5 = await Tour.create({ ratings: 4, desc: "Cool" })
    // const tour6 = await Tour.create({ ratings: 999, desc: "Cool" })
    
    // Test
    const query = Tour.find({desc: "Cool"})
    query.sort("ratings")
    
    const tours = await query
    console.log({ tours })
    

    This produced the expected output of only "Cool" tours sorted by rating. See how I used hardcoded values for sorting and finding? This leads me to believe that the issue is in the values.