2017-01-05 26 views
0

我正在根據自己的需要調整Microscope教程,並且難以編寫收集嵌入在帖子中的所有註釋的查詢。Mongo - 請求Post中的所有嵌入式註釋查詢

這裏是我的查詢到目前爲止: Posts.find({"postId": this._id}, {"comments":{}});

下面是一個例子文章,我想從評論:

{ 
"_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" 
} 
    ]} 

這似乎返回遊標,但我不能使用它的toArray()函數。

我讀這是不可能的(Filtering embedded documents in MongoDB),但是這是六年前......

我也看到了張貼關於$sliceaggregate,但似乎無法讓我的頭周圍。

任何幫助非常感謝!

+0

您是否訂閱了數據?爲什麼不簡單地使用'PostsfindOne(postId)'並從接收到的對象中提取所有註釋? – MasterAM

+0

該數據公佈:'Meteor.publish('comments',function(postId){ check(postId,String); return Posts.find({postId:postId}); });'這裏是router.route('/ posts /:_ id',{ name:'postPage', waitOn:function(){ return [ Meteor.subscribe('singlePost',this.params._id ), Meteor.subscribe( '評論',this.params._id) ]; }, 數據:功能(){返回Posts.findOne(this.params._id);} });' – sutebu

+0

如何我是否會從接收的對象中提取評論?例如:'var post = Posts.findOne({postId:this._id}); \t var commentList = post.comments.toArray();返回commentsList;'? 感謝MasterAM。 – sutebu

回答

0

查詢此 - > Posts.find({「comments.postId」:this._id});

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 
    }); 

我希望這有助於。

相關問題