NodeJS 过滤,分页和排序
作者:互联网
// GET /tasks?completed=true
// GET /tasks?limit=2&skip=2
// GET /tasks?sortBy=createdAt:desc
router.get("/tasks", auth, async (req, res) => {
const match = {};
const sort = {};
if (req.query.completed) {
match.completed = req.query.completed === "true";
}
if (req.query.sortBy) {
const parts = req.query.sortBy.split(":");
sort[parts[0]] = parts[1] === 'desc' ? -1 : 1;
}
try {
await req.user.populate({
path: "tasks",
match,
options: {
limit: parseInt(req.query.limit || 0),
skip: parseInt(req.query.skip || 0),
sort
},
});
res.send(req.user.tasks);
} catch (e) {
res.send(e);
}
});
标签:tasks,const,NodeJS,skip,completed,req,过滤,query,排序 来源: https://blog.csdn.net/ftell/article/details/120101234