router.get("/test/:id", async (req, res) => {
try {
var data = req.params.id;
var sortAs= 0;
if (data.localeCompare("0")) {
sortAs= "price";
} else {
sortAs= "rating";
}
let addwises = await Addwise.find()
.populate("reviews").sort({ sortAs: -1 })
.exec();
res.json({
success: true,
addwises: addwises,
});
} catch (err) {
res.status(500).json({
success: false,
message: err.message,
});
}
});
伙计们,这是我的代码,但是.sort()函数中的sortAs存在问题。它根本不会检测到该变量。我该怎么做才能使其可变。如果我输入“价格”或“评分”,则可以正常运行,但否则无法进行精确排序。
答案 0 :(得分:0)
使用ES6语法:
router.get("/test/:id", async (req, res) => {
try {
var data = req.params.id;
var sortAs= 0;
if (data.localeCompare("0")) {
sortAs= "price";
} else {
sortAs= "rating";
}
let addwises = await Addwise.find()
.populate("reviews").sort({ [sortAs]: -1 })
.exec();
res.json({
success: true,
addwises: addwises,
});
} catch (err) {
res.status(500).json({
success: false,
message: err.message,
});
}
});
或传递对象
router.get("/test/:id", async (req, res) => {
try {
var data = req.params.id;
var sortAs= {};
if (data.localeCompare("0")) {
sortAs["price"] =-1;
} else {
sortAs["rating"] = -1;
}
let addwises = await Addwise.find()
.populate("reviews").sort(sortAs)
.exec();
res.json({
success: true,
addwises: addwises,
});
} catch (err) {
res.status(500).json({
success: false,
message: err.message,
});
}
});