首页 > 解决方案 > 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 中的单个查询获取帖子详细信息,包括单个帖子的用户详细信息和个人评论的用户详细信息?

标签: javascriptmongodbmongoose

解决方案


您可能想使用 Mongoose 提供的“填充”方法:https ://mongoosejs.com/docs/populate.html

它允许您在架构定义中“链接”您的集合,并在单个查询中查询和填充所有相关集合,例如

Posts.findOne({ postId: 1 }).populate('user')

按照上面的文档链接了解有关如何编写模式的更多详细信息。


推荐阅读