Как собрать две коллекции из MongoDB с помощью Express? - PullRequest
1 голос
/ 03 октября 2019

Итак, у меня сейчас две коллекции. Один из них «посты», а другой «пользователи»

Это пост:

  • _id
  • title
  • text
  • пользователь
  • дата

и это пользователи:

  • _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'
        }
      }
    ]);

    // 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');
  }
});

Обратите внимание, что первая константа профиля закомментирована, но это однаЯ использую для извлечения данных пользователей в соответствии с _id ( req.params.user_id ) пользователя X.

Теперь я хотел бы отобразить все сообщения, созданные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 не является функцией». Надеюсь, я смог объяснить, спасибо!.

Я просто хочу добавить новое поле (массив записей) в коллекцию пользователей.

1 Ответ

0 голосов
/ 04 октября 2019

Если кто-то пришел к такому же требованию, как и я, то вот решение после двух дней исследования и вопроса. Lol.

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');
  }
});
...