Mongoose query with sorting is not working

563 Views Asked by At

I'm trying to implement a basic sorting function to queries to my mongoDB database, but I'm getting stuck. Here is the function:

    exports.getAllFamilyPlots = async (req, res) => {
  try {
    //BUILD QUERY
    const queryObj = { ...req.query };
    const excludedFields = ['page', 'sort', 'limit', 'fields'];
    excludedFields.forEach((el) => delete queryObj[el]);

    let queryStr = JSON.stringify(queryObj);
    queryStr = queryStr.replace(/\b(gte|gt|lte|lt)\b/g, (match) => `$${match}`);

    let query = await Plot.find(JSON.parse(queryStr));

    //SORTING
    if (req.query.sort) {
      query = query.sort(req.query.sort);
    }
    //EXECUTE QUERY
    const plots = await query;

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

I tried putting the query in into postman, by putting "?sort=size" at the end of my route. I just get the following:

{
    "status": "fail",
    "message": {}
}

logging "req.query.sort" to the console gives me "size", just like I entered it in postman. Logging "query" gives the 4 objects from my database, but logging it after the sorting line gives me absolutely nothing. Even if I try to hardcode it with query.sort(size);it still logs nothing to the console. Am I using the .sort function from mongoose wrong, or what is going on?

3

There are 3 best solutions below

0
Hanama Namana On

Fixed it by removing "await" from this line;

let query = await Plot.find(JSON.parse(queryStr));

at line 11 of the code I posted above.

0
Yajindra Gautam On

I also face the same problem while making projects but I was fixed it. Follow all steps carefully.

  1. Remove 'await' from this line of code.
let query = await Plot.find(JSON.parse(queryStr));
  1. Make sure you have not used const as you are reassigning the value of the query variable.
  2. Use this code
let query = Tour.find(JSON.parse(queryStr));

    // 2) Sorting
    if (req.query.sort) {
      query = query.sort(req.query.sort);
    }
0
Tipu Sultan On
if (req.query.sort && typeof req.query.sort === 'function') {
  query = query.sort(req.query.sort);
}