Mongoose 查询:从 Post 模式中填充前 2 条评论

Mongoose query: populate top 2 comments from Post Schema

我有 3 个集合:用户、Post 和评论。 Posts 有多个评论。 我想抓取 50 个帖子,填充作者,填充评论,但我只想要按日期排序的前 2 个投票最多的评论(_id)

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 来自定义您的人口。在这种情况下 limit 为 2.

试试这个:

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

如果你想要更多的自定义,你可以使用mongoose Query conditions(select,匹配,模型,路径等)和options一起使用。

阅读 Mongoose Population documentation 了解更多详细信息。