【发布时间】:2021-09-27 23:06:09
【问题描述】:
我需要帮助创建一个 mongoose 查询,该查询在用户集合中找到请求用户的喜欢,然后在帖子集合中搜索用户的喜欢。希望有人能告诉我我在查询中做错了什么,或者我怎样才能做得更好。
用户和帖子集合:
const users = [
{
_id: "1",
likes: ["1", "2"]
},
{
_id: "2",
likes: ["3"]
}
]
const posts = [
{
_id: "1",
stuff: "stuff1"
},
{
_id: "2",
stuff: "stuff2"
},
{
_id: "3",
stuff: "stuff3"
}
]
聚合查询:
router.post("/", authUser, async (req, res) => {
User.aggregate([
{
$match: {
_id: ObjectId(req.user._id), //user 1
},
},
{
$unwind: "$likes",
},
{
$lookup: {
from: "posts",
let: { like: "$likes" },
pipeline: [
{
$match: {
$expr: {
$eq: ["_id", "$$like"],
},
},
},
],
as: "matched_posts",
},
},
{
$unwind: "$matched_posts",
},
]).then((d) => {
console.log(d);
});
});
期望的输出:
const output = [
{
_id: "1",
stuff: "stuff1"
},
{
_id: "2",
stuff: "stuff2"
}
]
【问题讨论】:
标签: mongodb express mongoose aggregation-framework