我需要帮助在Express中使用mongooose数据库进行排序。当我使用sort({'price':1})时,一切都很好,但是当我传递JSON.stringify(sort)时,它包含并注销{“price”:1},它就停止工作了。知道为什么吗?
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,
});
}
};
1条答案
按热度按时间fcg9iug31#
How to sort in mongoose?
.sort()接受一个对象,但不接受字符串。您使用了JSON.stringify(sort),它将
sort
查询转换为字符串,因此mongoose无法解析它。