2016-12-05 77 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' }] 
}); 
相关问题