My mongoose model for a post on a social networking platform is called PostModel:
{
caption: String,
likes: [] // array to store information about users who liked the video, essentially referencing another model
comments: [] // array to hold comment objects
}
I am trying to sort all the posts in a find query based on the number of likes, which is the length of the "likes" array. In case of posts with equal likes, I want to further sort them by the number of comments, i.e., the length of the "comments" array.
The sorting method I attempted seems to be not working as expected. Here is what I tried:
PostModel.find({}, {
likes: { $size: "$likes" },
comments: { $size: "$comments" }
},
{
sort: { likes: -1, comments: -1 } // encountered error message "cannot sort with keys that are parallel arrays"
})
This issue made me suspect that the sorting operation occurs prior to projection. To verify this, I executed the following query:
PostModel.find({}, {
_l: { $size: "$likes" },
_c: { $size: "$comments" }
},
{
sort: { _l: -1, _c: -1 }
})
Although this query did not produce any errors, it failed to sort the resulting array altogether. Hence, it confirmed my suspicion that projection takes place after sorting in mongoose.
In this scenario, how can I properly sort the array based on both the number of likes and comments?