Sort with Mongoose

For some reason, I can’t sort with multiple parameters in Mongoose. One parameter works just fine, but the ones after that are not working.

My query looks like this : 127.0.0.1:3000/api/v1/tours?sort=ratingsAverage,price

exports.getAllTours = async (req, res) => {
        const queryObj = { ...req.query }; 

        let query = Tour.find(queryObj);

        if (req.query.sort) {
          const sortBy = req.query.sort.split(',').join(' ');
          query = query.sort(sortBy);
        } 
        
    const tours = await query;

        res.status(200).json({
          status: 'success',
          requestedAt: req.requestTime,
          results: tours.length,
          data: {
            tours
          }
        });
      } catch (err) {
        res.status(404).json({
          status: 'fail',
          message: err
        });
      }
    };

Hello @Frederic_Ferreira, Welcome to the MongoDB community developer forum,

As per your query, it looks good, You need to provide more debugging details like,

  • confirm by printing the value of sortBy variable in the console, is it getting the exact value "ratingsAverage price"?
  • Please provide some example documents and expected results and what are you currently getting the unexpected result so we can investigate the problem.

Hello @turivishal, thank you :slight_smile:
I took some screenshots of what you recommended, and as we can see the console print the two query parameters when logging sortBy (here I tried with price and duration). Also we can see on postman that, the results are correct for the first parameter (price) but not the second (duration), they are not sorted by duration.

Here are the screenshots :

Hi @Frederic_Ferreira welcome to the community!

I think the issue is that the sort parameters was somehow not passed properly into mongoose. However, the code example you posted and the screenshot are showing different things: the code example looks like it’s one script, while the screenshot shows that the sorting processing was done in a function called sort().

What I would do in this situation is to manually step through the code to make sure that all the parameters are processed correctly, and the mongoose query was constructed correctly.

If you need further help, could you post a self-contained code that can reproduce this? E.g., you mentioned that this was called using the URI 127.0.0.1:3000/api/v1/tours?sort=ratingsAverage,price so I would also include the basic Express (?) code, so that we can work from a common source and not guessing on how your Express code looks like (and end up diverging since I could code it differently :slight_smile: )

Best regards
Kevin

4 Likes