【发布时间】:2021-11-04 08:11:28
【问题描述】:
我想在聚合阶段之后根据条件获取结果。我的代码给了我一个包含 4 个结果而不是 3 个的数组。 逻辑是用户滑动并将数据存储在一个集合中。集合存储第一次滑动,如果其他用户滑动现有条目,则更新集合文档而不是新插入,这取决于谁先滑动,因此 $or 查询。这工作正常,直到我在用户集合上将现有用户的连接状态更改为 false。结果是一个长度为 4 而不是 3 的数组。额外的数组是从 $or 查询创建的,并且只有 user_two。
滑动收藏 _id(ObjectID) - user_one(string) - user_two(string) - status_one(number) - status_two(number)
用户收藏 _id(ObjectID) - user_name(string) - hookups(boolean)
const fetchHookups = (req, res, next) => {
var query = {
$or: [
{ user_one: ObjectId(req.body._id)},
{ user_two: ObjectId(req.body._id) },
]
}
Swipe.aggregate([{
$match: query
},
{
$lookup: {
from: 'users',
let: { user_one: '$user_one', hookupstatus: true },
pipeline: [{
$match: {
$expr: {
$and: [
{ $eq: ["$_id", '$$user_one'] },
{ $eq: ["$hookups", '$$hookupstatus'] },
],
}
}
}],
as: "userone"
}
},
{
$unwind: {
path: "$userone",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'users',
let: { user_two: '$user_two', hookupstatus: true },
pipeline: [{
$match: {
$expr: {
$and: [
{ $eq: ["$_id", '$$user_two'] },
{ $eq: ["$hookups", '$$hookupstatus'] },
],
}
}
}],
as: "usertwo"
}
},
{
$unwind: {
path: "$usertwo",
preserveNullAndEmptyArrays: true,
},
},
{
$sort: {
_id: -1
}
}
]).exec(function(error, response) {
if (error) {
console.log(error)
} else {
res.json(response)
}
})
}
【问题讨论】:
标签: javascript node.js angular mongodb ionic-framework