繁体   English   中英

如何循环遍历mongo和nodejs中的嵌套对象数组?

[英]How to loop through a nested array of objects in mongo and nodejs?

我收集了一系列帖子,每个帖子看起来像这样:

{Post: 
    [ 
        id: 'post_id',
        postedBy: 'user_id',
        likes: [0: id: 'user_id', 1: id: 'user_id'],
        content: 'text here',
        comments: [0: {id: 'comment_id', text: 'text here', postedBy: 'user_id'},
                   1: {id: 'comment_id', text: 'text here', postedBy: 'user_id']
        image: {url: 'image url here'}
    ],
    [ 
        id: 'post_id',
        postedBy: 'user_id',
        likes: [0: id: 'user_id', 1: id: 'user_id'],
        content: 'text here',
        comments: [0: {id: 'comment_id', text: 'text here', postedBy: 'user_id'},
                   1: {id: 'comment_id', text: 'text here', postedBy: 'user_id']
        image: {url: 'image url here'}
    ],
}

我希望能够在所有帖子中找到特定用户创建的所有评论。

我知道我可以通过执行以下操作找到特定用户创建的帖子:

const post = await Post.find({ postedBy: some user_id });

我还知道,如果我知道我正在寻找的评论的索引,我可以这样做:

const comment = await Post.find({ comments[0].postedBy: some user_id })

但是我正在努力弄清楚如何循环遍历像这样的嵌套索引对象数组以找到我需要的数据。 TIA

文档中,我发现了$elemMatch运算符,因此我能够访问包含由特定用户撰写的评论的所有帖子,如下所示:

const posts = await Post.find({
  comments: { $elemMatch: { postedBy: user_id } },
});

然后我可以通过返回的数组 map 来访问评论本身,如下所示:

const comments = posts.map((item) => item.comments);

希望有一天这对其他人有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM