Mongo - request all embedded comments in Post query

时间:2017-01-05 10:38:22

标签: mongodb meteor

I'm adapting the Microscope tutorial to my needs and am having difficulty writing a query which gathers all the comments embedded within a post.

Here is my query so far: Posts.find({"postId": this._id}, {"comments":{}});

Here is an example post I want to get the comments from:

{
"_id": "Ad9RYqWqbsJKZx3h7",
  "title": "Writing decimal number words as a decimal number",
  "userId": "9yqTaFeQSqvKmNn8B",
  "author": "Sacha Greif",
  "submitted": "2017-01-05T03:26:18.908Z",
  "commentsCount": 4,
  "comments": [
{
  "body": "Hello",
  "postId": "Ad9RYqWqbsJKZx3h7",
  "userId": "73qGvsRuqNtXcaZDx",
  "author": "student",
  "submitted": "2017-01-05T10:26:45.745Z"
},
{
  "body": "How are you?",
  "postId": "Ad9RYqWqbsJKZx3h7",
  "userId": "73qGvsRuqNtXcaZDx",
  "author": "student",
  "submitted": "2017-01-05T10:28:17.225Z"
}
  ]}

It seems to return a cursor, but I am not able to use the toArray() function on it.

I have read this is not possible (Filtering embedded documents in MongoDB), but this was six years ago...

I've also seen posts about $slice and aggregate but can't seem to get me head around them.

Any help much appreciated!

2 个答案:

答案 0 :(得分:0)

查询此信息> Posts.find({" comments.postId":this._id});

答案 1 :(得分:0)

您只需使用findOne从集合中获取特定文档,就可以使用forEach循环来遍历该文档的comments数组。

var post = Posts.findOne({_id: "<id_of_the_post>"});

var post_comments = post.comments; // post_comments contains the comments array

或者如果您想对每个评论使用forEach

    post_comments.forEach(function(entry, index, arr){
    // entry has the comment object 
//do something with the comment
    });

我希望这会有所帮助。