2
votes

I have 3 collections: User, Post and Comment. Posts has multiple comments. I want grab 50 posts, populate author, populate comments but I want only top 2 most voted comments sorted by date(_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')
  ...

and I dont know how to achieve this.

1

1 Answers

2
votes

you can use mongoose populate options to customize your population. In this case limit it to 2.

Try this:

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

In case you want more cusomization, you can use mongoose Query conditions(select, match, model, path etc.) and options together.

Read Mongoose Population documentation for more detailed information.