Mongoose查询:从Post Schema中填充前两个评论

我有3个集合:用户,发布和评论。 post有多个评论。 我想抓住50个职位,填充作者,填充评论,但我只想要按date(_id)sorting前2个最多投票评论

const PostSchema = new Schema({ author: { type: Schema.Types.ObjectId, ref: 'User' }, content: String, comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }] }); const Post = mongoose.model('Post', PostSchema); const CommentSchema = new Schema({ author: { type: Schema.Types.ObjectId, ref: 'User' }, content: String, votes: Number }); const Comment = mongoose.model('Comment', CommentSchema); Post .find({}) .limit(50) .populate('author') .populate('comments') ... 

我不知道如何做到这一点。

你可以使用mongoose populate options来定制你的人口。 在这种情况下limitlimit为2。

尝试这个:

 Post .find({}) .limit(50) .populate('author') .populate({ path :'comments', options : { sort: { votes: -1 }, limit : 2 } }); 

如果你想更多的cusomization,你可以使用mongoose mongoose Query conditions (select,匹配,模型,path等)和options一起。

阅读mongoose种群文档以获取更多详细信息。