【发布时间】:2021-05-16 23:04:17
【问题描述】:
想法:我想在多种条件下对我的产品进行排序,例如按 createdAt 按 desc 或 asce 排序、按价格排序等。 问题:两者都工作正常,但是我如何根据用户的请求检查需要排序的内容,我们需要按 createdAt 或 price 对产品进行排序。
这是代码。
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 排序而不是按价格排序。
Input: 1 //按价格排序产品 输出:按 createdAt 排序的产品 //但我需要价格
【问题讨论】:
-
您应该只查询一次数据,然后将其呈现以使其按任意值排序。