2016-12-05 80 views
2

因此,假設我有3個博客作者。他們每個人都有很多帖子。爲集合中的每個博客選擇最新帖子

我想選擇每個人的最新帖子。

目前我有這樣的僞代碼:

Bloggers.find({name: {$in: ['John','Mike','Arny']}}, (err, bloggers) => { 
    bloggers.forEach(blogger => { 
     blogger.latest_post = Posts.find({author: blogger.name}).sort({date: -1}).limit(1); 
    }) 
    displayItSomehow(bloggers); 
}) 

這裏,博客的名字是一組名稱。每個組都有很多文檔,但我只需要一個相應的標準。

博客收集這樣的:

{name: 'John', id: 1}, 
{name: 'Mike', id: 2}, 
{name: 'Arny', id: 3} 

帖子集合:

{ title: 'title1', text: 'blablabla', date: 111, author: 1 }, 
{ title: 'Nowadays football became...', text: 'blablabla', date: 112, author: 1 }, 
{ title: 'title1', text: 'blablabla', date: 113, author: 2 }, 
{ title: 'The story of my neighbor starts when...', text: 'blablabla', date: 114, author: 2 }, 
{ title: 'title1', text: 'blablabla', date: 115, author: 3 }, 
{ title: 'title1', text: 'blablabla', date: 116, author: 3 }, 
{ title: 'Business and success are always were...', text: 'blablabla', date: 117, author: 3 } 

結果應該是這樣的:

John:  'Nowadays football became...' 

Mike:  'The story of my neighbor starts when...' 

Arny:  'Business and success are always were...' 

所以,我怎麼能真正解決我的問題在貓鼬?一個查詢可能嗎?

+1

請將樣本集合添加到博客和帖子的帖子 – Veeram

+0

是t帽子更好?) –

回答

0

查詢population是你在找什麼:

Bloggers 
    .find({name: {$in: ['John','Mike','Arny']}}) 
    .populate({ 
     path: 'posts', 
     options: { 
      limit: 1, 
      sort: {date: -1} 
     } 
    }) 
    .exec((err, bloggers) => { 
     displayItSomehow(bloggers); 
    }) 
}) 

下面是對文檔的鏈接配置對象的填入功能:http://mongoosejs.com/docs/api.html#model_Model.populate

這隻會工作,如果你定義Bloggers架構相應:

var bloggerSchema = Schema({ 
    _id  : Number, 
    name : String, 
    // all your other fields... 
    posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }] 
}); 
相關問題