为集合中的每个博主select最新post

所以,假设我有3个博主。 他们每个人都有很多职位。

我想为他们每个人select最新的职位。

目前我有这个伪代码:

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

在这里,博客的名字是一个组的名称。 每个小组都有很多文档,但我只需要一个相应的标准。

像这样的Blogger集合:

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

post集合:

 { 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...' 

那么,我怎样才能解决我的问题,实际上在mongoose? 一个查询可能吗?

查询人口是你在找什么:

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

下面是configuration对象到填充函数的文档的链接: 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' }] });