【问题标题】:Mongoose query: populate top 2 comments from Post SchemaMongoose 查询:填充来自 Post Schema 的前 2 条评论
【发布时间】:2017-07-13 15:34:50
【问题描述】:

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

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

我不知道如何实现这一点。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query mongoose-populate


    【解决方案1】:

    您可以使用mongoose populate options 自定义您的人口。在这种情况下,limit 是 2。

    试试这个:

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

    如果您想要更多的自定义,您可以同时使用mongoose Query conditions(选择、匹配、模型、路径等)和options

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

    【讨论】:

    • 谢谢,这行得通:Post .find({}) .limit(50) .populate('author') .populate({ path :'comments', options : {sort: { votes: -1}, limit : 2} });
    猜你喜欢
    • 1970-01-01
    • 2019-11-12
    • 2013-07-06
    • 2021-03-03
    • 1970-01-01
    • 2012-07-03
    相关资源
    最近更新 更多