использовать синтаксис 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,
});
}
});