在 Nodejs 中,我想在 mongoose 查询中使用 .sort() 方法来实现升序/降序功能。它在输入硬编码的“标题”或“-标题”时有效,但我想让它依赖于用户条目,该条目应该由变量表示。使用变量时,它无法识别我的字符串。
这不起作用:
const filterForMovie = async(req,res)=>{
try {
let {title, publishDate, genre, skip, limit, sort} = req.query;
const queryObject = {};
if(title){
queryObject.title = title;
}
if(publishDate){
queryObject.publishDate = publishDate;
}
if(genre){
queryObject.genre = genre;
}
if(sort){
sort === "Ascending" ? sort = "-title" : sort = "title";
}
let data = await Movie.find(queryObject).limit(Number(limit)).sort(sort).skip(Number(skip));
res.status(200).json(data);
} catch (error) {
console.log(error)
}
}
将变量更改为实际的字符串即可:
const filterForMovie = async(req,res)=>{
try {
let {title, publishDate, genre, skip, limit, sort} = req.query;
const queryObject = {};
if(title){
queryObject.title = title;
}
if(publishDate){
queryObject.publishDate = publishDate;
}
if(genre){
queryObject.genre = genre;
}
if(sort){
sort === "Ascending" ? queryObject.sort = "-title" : queryObject.sort = "title";
}
let data = await Movie.find(queryObject).limit(Number(limit)).sort("title").skip(Number(skip));
res.status(200).json(data);
} catch (error) {
console.log(error)
}
}
到底为什么该变量不被视为有效的排序标准。
typeof sort
显示字符串。
而不是使用这个:
sort === "Ascending" ? sort = "-title" : sort = "title";
尝试正确使用条件(三元)运算符:
sort = sort === "Ascending" ? "-title" : "title";