javascript - MongoDB 与子文档的多重连接
问题描述
我有两个系列,
用户集合:
{
"userId": 1,
"name": 'John',
"profile": 'john.png'
},
{
"userId": 2,
"name": 'Doe',
"profile": 'doe.png'
},
{
"userId": 3,
"name": 'John Doe',
"profile": 'johndoe.png'
}
帖子集合:
{
"postId": 1,
"userId": 1,
"postContent": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"comments": [
{
"comment": "sample comment",
"commentedBy": 2,
},
{
"comment": "Another sample comment",
"commentedBy": 3,
}
],
}
如何通过 mongoose 中的单个查询获取帖子详细信息,包括单个帖子的用户详细信息和个人评论的用户详细信息?
解决方案
您可能想使用 Mongoose 提供的“填充”方法:https ://mongoosejs.com/docs/populate.html
它允许您在架构定义中“链接”您的集合,并在单个查询中查询和填充所有相关集合,例如
Posts.findOne({ postId: 1 }).populate('user')
按照上面的文档链接了解有关如何编写模式的更多详细信息。
推荐阅读
- c++ - 使用重载 >> 从文件创建对象正在创建空白对象(C++)
- javascript - 构造函数原型上的方法在调用时抛出 TypeError
- windows - First React Native Windows App - 在 VSCode 中运行调试返回错误
- python - 我需要确定如何绘制搜索词数据中另一个变量(国家)使用的最常用词以及相应的国家
- python - 我想在 aws lambda (python) 中使用 ffmpeg 打印 HLS 文件
- capacitor - 如何拥有全屏capacitor.js无缝iframe
- python - PySpark array_remove 元素正则表达式问题
- javascript - 将 javascript 正则表达式转换为 posix 正则表达式
- sql - 使用 Hiveql 计算表的列数
- php - 如何使用 PHP 显示 PDF 文件