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?
Fixed it by removing "await" from this line;
at line 11 of the code I posted above.