为集合中的每个博主选择最新帖子

时间:2016-12-05 17:26:18

标签: node.js mongodb mongoose

所以,假设我有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);
})

此处,博主的名称是组的名称。每个小组都有很多文档,但我只需要一个相应的标准。

这样的Blogger集合:

{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 个答案:

答案 0 :(得分: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' }]
});