mongodb - 如何使用 Express 从 MongoDB 聚合两个集合?
问题描述
所以我目前有两个系列。一个是“帖子”,另一个是“用户”
这是帖子:
- _ID
- 标题
- 文本
- 用户
- 日期
这是用户:
- _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');
}
});
请注意,第一个配置文件常量已被注释,但这是我用来根据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 数组)。
解决方案
如果有人像我一样提出了同样的要求,这是经过两天的研究和询问后的解决方案,哈哈。
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');
}
});
推荐阅读
- ajax - Ajax 发布到 aws api-gateway 返回访问控制检查响应
- vb.net - 在“绑定”数据网格视图中设置工具提示
- sql - presto/aws athena - 选择最新版本的记录
- python - 熊猫:如何在情节中标记分组数据?
- php - 上传的图像文件不能使用 phpmailer 内嵌在电子邮件正文中
- javascript - 如何将 jQuery 插件导入 babel 应用程序
- python - 自动使 matplotlib 图像与其他子图标签齐平
- c# - Web API ChangePasswordAsync 控制器返回失败:PasswordMismatch C#
- networking - Kubernetes 请求服务超时值
- python - Python:创建列表列表作为字典值