首页 > 解决方案 > 如何使用 Express 从 MongoDB 聚合两个集合?

问题描述

所以我目前有两个系列。一个是“帖子”,另一个是“用户”

这是帖子:

这是用户:

我正在尝试通过以下方式使用聚合:

router.get('/:user_id', async (req, res) => {
  try {
    // const profile = await User.findById(req.params.user_id);
    const profile = await User.agregate([
      {
        '$lookup': {
          'from': 'posts',
          'localField': '_id',
          'foreignField': 'user',
          'as': 'posts'
        }
      }
    ]);

    // Verify profile exists
    if (!profile) return res.status(400).json({ msg: 'Profile not found' });

    res.json(profile);
  } catch (err) {
    console.error(err.message);
    if (err.kind == 'ObjectId') {
      return res.status(400).json({ msg: 'Profile not found' });
    }
    res.status(500).send('Server error');
  }
});

请注意,第一个配置文件常量已被注释,但这是我用来根据X 用户的 _id( req.params.user_id ) 获取用户数据的那个。

现在我想创建的是通过访问他们的个人资料来显示由 X 用户创建的所有帖子,所以我需要匹配相应的用户,我需要传递req.params.user_id

这是我没有工作的新代码:

router.get('/:user_id', async (req, res) => {
  try {
    // const profile = await User.findById(req.params.user_id);
    const profile = await User.agregate([
      {
        '$lookup': {
          'from': 'posts',
          'localField': '_id',
          'foreignField': 'user',
          'as': 'posts'
        }
      }, {
        $unwind: "$posts"
      }, {
        $match: {
          "posts.user": req.params.user_id
        }
      }
    ]);

    // Verify profile exists
    if (!profile) return res.status(400).json({ msg: 'Profile not found' });

    res.json(profile);
  } catch (err) {
    console.error(err.message);
    if (err.kind == 'ObjectId') {
      return res.status(400).json({ msg: 'Profile not found' });
    }
    res.status(500).send('Server error');
  }
});

我的 console.log 中显示的错误是“user.aggregate 不是函数”。希望我能解释一下自己,谢谢!

我只想在 users 集合中添加一个新字段(posts 数组)。

标签: mongodbexpressmern

解决方案


如果有人像我一样提出了同样的要求,这是经过两天的研究和询问后的解决方案,哈哈。

router.get('/:user_id', async (req, res) => {
  try {
    const userId = req.params.user_id;
    const [profile, postsByUser] = await Promise.all([User.findById(userId, '-password'), Post.find({ user: userId }).populate('user', ['_id', 'username', 'avatar']).sort({ date: -1 })]);

    // Verify profile exists
    if (!profile) return res.status(400).json({ msg: 'Profile not found' });

    // res.json(profile);
    res.json({ ...profile.toJSON(), postsByUser });
  } catch (err) {
    console.error(err.message);
    if (err.kind == 'ObjectId') {
      return res.status(400).json({ msg: 'Profile not found' });
    }
    res.status(500).send('Server error');
  }
});

推荐阅读