Итак, у меня сейчас две коллекции. Один из них «посты», а другой «пользователи»
Это пост:
- _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 не является функцией». Надеюсь, я смог объяснить, спасибо!.
Я просто хочу добавить новое поле (массив записей) в коллекцию пользователей.