【问题标题】:Query and Match from Two Database Collections (Mongoose/MongoDB)从两个数据库集合(Mongoose/MongoDB)中查询和匹配
【发布时间】: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


    【解决方案1】:
    • $match你的条件
    • $lookup 与帖子集合,传递 likes 作为 localField_id 作为 foreignField
    • $unwind解构likes数组
    • $replaceRoot 替换 likes 对象
    router.post("/", authUser, async (req, res) => {
      User.aggregate([
        { $match: { _id: ObjectId(req.user._id) } },
        {
          $lookup: {
            from: "posts",
            localField: "likes",
            foreignField: "_id",
            as: "likes"
          }
        },
        { $unwind: "$likes" },
        { $replaceRoot: { newRoot: "$likes" } }
      ])
      .then((d) => {
        console.log(d);
      });
    });
    

    Playground

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2020-03-24
      • 1970-01-01
      • 2017-10-22
      相关资源
      最近更新 更多