Idea:我想在多种条件下对我的产品进行排序,如按createdAt或asce排序,按价格排序等等。发布:两者都运行良好,但我如何检查用户的要求,需要排序哪些产品,或者我们需要按createdAt或价格排序。
这是密码。
const getProducts = async (req, res) => {
try {
const sortQuery = req.query.sort;
console.log(sortQuery);
const productMessages = await productMessage
.find({})
.sort({
createdAt: sortQuery,
price: sortQuery,
})
.populate("categoryId")
.exec();
// const productMessages = await productMessage.find();
res.status(201).json(productMessages);
} catch (error) {
res.status(404).json({ message: error.message });
}
};在这里,如果我发送查询按价格对产品进行排序,它会给出按createdAt排序的产品,而不是按价格排序的结果。
输入:1//按价格排序产品输出:按createdAt //排序的产品//但我需要有价格
发布于 2021-05-16 15:04:17
您可以在执行之前进行检查。
喜欢
const getProducts = async (req, res) => {
try {
const sortQuery = req.query.sort;
console.log(sortQuery);
let sortObject = {};
if (req.query.sortField == "createdAt") {
sortObject["createdAt"] = sortQuery
} else if (req.query.sortField == "price") {
sortObject["price"] = sortQuery
}
const productMessages = await productMessage
.find({})
.sort(sortObject)
.populate("categoryId")
.exec();
// const productMessages = await productMessage.find();
res.status(201).json(productMessages);
} catch (error) {
res.status(404).json({ message: error.message });
}
};您必须在查询中传递sortField。
https://stackoverflow.com/questions/67558110
复制相似问题