I am trying to sort my data by price, descending. In the following controller, I am able to filter for operations like greater than less than, less than or equal to... However, I create an if statement to check if a query has sort (localhost:3000/api/v1/tours?sort=price) and it does, so then in the block code, I am trying to sort. What ends up happening with the code below is the error
{
"status": "failure",
"results": "Parameter \"filter\" to find() must be an object, got price"
}
我在上一门课,学生们用Mongoose 5,而我用6。每当我用其他代码,比如--if语句--
if (queryString.sort) {
queryString = queryString.sort(req.query.sort);
}
就会出现这样的错误
{
"status": "failure",
"results": "queryString.sort is not a function"
}
在我的 Postman 应用程序中。看起来我的if语句中的代码几乎被忽略或踩进了错误。
exports.getAllTours = async (req, res) => {
try {
let queryString = JSON.stringify(req.query);
queryString = queryString.replace(
/\b(gte|gt|lte|lt)\b/g,
(match) => `$${match}`
);
let = queryString = JSON.parse(queryString);
if (queryString.sort) {
queryString = queryString.sort;
}
const tours = await Tour.find(queryString);
res
.status(200)
.json({ status: 'ok', results: tours.length, data: { tours } });
//TODO: Will fine tune error despite somewhat working
} catch (err) {
// eslint-disable-next-line no-console
console.log(err);
res.status(404).json({ status: 'failure', results: err.message });
}
};
以下是我的一些问题:
1.在这种情况下,如何正确地使用Mongoose的排序函数?
3条答案
按热度按时间smdnsysy1#
如果您想同时进行筛选和排序,则可以尝试
vjrehmav2#
我意识到必须在find方法中使用JSON.parse。
8ljdwjyq3#
将查询代码放入if语句中以查找()所有数据,然后添加
.sort()
方法。如果您想按价格排序,并且只显示符合条件的数据,您可以尝试以下操作:
更多信息,您可以访问MongoDB
.sort()