node.js - MERN中的排序
问题描述
想法:我想在多种条件下对我的产品进行排序,例如按 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 排序而不是按价格排序。
输入:1 //按价格排序产品输出:按createdAt排序的产品//但我需要价格
解决方案
您可以在执行前进行检查。
喜欢
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。
推荐阅读
- html - 按宽度拆分 div 以填充父 div
- javascript - 在鼠标事件的 for 循环中赋值
- lua - lua 代码工作,但在代码完成之前停止
- ios - 有没有免费的方法可以使用 Phonegap 为 iOS 设备进行开发?
- flutter - Flutter:升级androidcompiledSdkVersion
- python - 如何使用小部件列表
- python - 如何在读取多个文件时提供编码?
- java - 具有 @DiscriminatorValue 的多个对象的单个存储库
- c++ - CMake 链接说明
- java - 使用自定义标签将 struts 1.3 迁移到 spring - 需要帮助