Mário João
Mário João

Reputation: 45

How to make aggregation return the rest of post?

Hey guys I wanted to ask the best way for me to use the conditions.

I am doing this by using aggregate, I am trying to return my top 5 most liked posts, but the only thing I return is the id and the number of likes the post has,

const posts = await Post.aggregate([
      {
        $project: {
          User: 1,
          numberOfLikes: {
            $cond: {
              if: {
                $isArray: "$likes",
              },
              then: {
                $size: "$likes",
              },
              else: "NA",
            },
          },
        },
      },
    ]); 

This is my model:

const PostSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId
  },
  text: {
    type: String,
    required: true
  },
  name: {
    type: String
  },
  avatar: {
    type: String
  },
  likes: [
    {
      user: {
        type: Schema.Types.ObjectId
      }
    }
  ])

Upvotes: 1

Views: 22

Answers (1)

turivishal
turivishal

Reputation: 36134

  • $count number of likes using $size operator
  • $sort by numberOfLikes in descending order
  • $limit to return 5 top posts
const posts = await Post.aggregate([
  { $set: { numberOfLikes: { $size: "$likes" } } },
  { $sort: { numberOfLikes: -1 } },
  { $limit: 5 }
])

Playground

Upvotes: 1

Related Questions