I need help with sorting in Express working with mongooose db. When i use sort({'price':1}) everythink is good, but when i pass JSON.stringify(sort) which contains and logs out {"price":1} it stops working. Any ideas why?
if(req.query.sortOption){
const str = req.query.sortOption.split(':');
sort[str[0]] = str[1] === 'desc' ? -1:1;
}
console.log(JSON.stringify(sort));
//here logs out {"price":-1} which works when i pass it into sort function as a string
try {
const annoucements = await Annoucement.find(query)
.skip(page * annoucementsPerPage)
.limit(annoucementsPerPage)
.populate('author')
.sort(JSON.stringify(sort))
res.status(200).json({
status: 'Successfully got an annoucement',
results: annoucements.length,
data: {
annoucements,
},
});
} catch (error) {
res.status(500).json({
status: 'Failed to get all annoucements',
message: error,
});
}
};
CodePudding user response:
.sort() takes in an object, and does not take in a string. You used JSON.stringify(sort), which made the sort
query into a string, hence mongoose could not parse it.
CodePudding user response:
Solution:
You should just pass .sort(sort)
instead of transforming the object to a string.
Explanation:
Mongoose either accepts
- a string like
"price"
(for ascending order) or"-price"
(for descending order). - an array (not applicable in this case)
- an object, where the key is the property name and the value is the order (
1
,"asc"
,"ascending"
or-1
, '"desc",
"descending"`)
What you did was basically pass the string value "{price:-1}"
to it, which does not match any of the use cases. Therefore your sorting does not work as expected.