我在猫鼬中进行的两个查询存在一些逻辑问题。我有两个查询,我想“合并”。 第一个查询进行非匿名调查,第二个查询进行匿名调查。区别在于,第一个我选择了“作者”字段,而第二个我没有选择“作者”字段。
现在我需要进行分页以加载民意调查,而我认为最好只执行一个查询。
因此,这些是查询:
let notAnonymousPolls = await Poll.find({toUser: user.id, anonymous: false, status: ["closed", "opened", "hidden", "waitingResponse"]})
.populate([
{path: "replies", select: "text"}, {path: "author", select: "username"}, {path: "replySelected", select: "_id"}
])
.select({"__v": 0});
秒
let anonymousPolls = await Poll.find({toUser: user.id, anonymous: true, status: ["closed", "opened", "hidden", "waitingResponse"]})
.populate([
{path: "replies", select: "text"}, {path: "replySelected", select: "_id"}
])
.select({"author": 0, "__v": 0});
我的问题是:如果匿名字段为假,我如何告诉猫鼬选择作者,否则,我告诉不选择作者? >
我不知道该怎么做,我不知道可以使用哪个运算符。我搜索了Mongoose文档,但没有发现任何帮助。
关于分页:如果我有一个查询,这很简单。如果我有两个查询,如何进行分页?使用$ slice运算符?
答案 0 :(得分:0)
一天后,我解决了问题。有人可以判断汇总,它是有效还是无效(如果出现问题,请给我建议)?
allPolls = await Poll.aggregate([
{
$match: {
"toUser": ObjectID(user.id),
$or: [
{status: "opened"},
{status: "closed"},
{status: "hidden"},
{status: "waitingResponse"}
]
}
},
{
$lookup: {
"from": "replies",
"localField": "replies",
"foreignField": "_id",
"as": "replies"
}
},
{
$lookup: {
"from": "replies",
"localField": "replySelected",
"foreignField": "_id",
"as": "selectedReply"
}
},
{
$lookup: {
"from": "users",
"localField": "author",
"foreignField": "_id",
"as": "creator"
}
},
{
$project: {
status: 1,
toUser: 1,
_id: 1,
createdAt: 1,
question: 1,
replies: 1,
anonymous: 1,
"replySelected._id": 1,
"author.username": {
$cond: {
if: "$anonymous", then: null, else : "$creator.username"
}
},
"author._id": {
$cond: {
if: "$anonymous", then: null, else : "$creator._id"
}
},
}
},
{
$skip: 0
},
{
$limit: 2
}
]);
(我尝试使用固定的跳过/限制)