How to use one virtual column to make another virtual column in mongoose?

Viewed 37

The scenario is, in the api that I am working on, there is an endpoint for stories where I have to take the average of no of views and no of comments, and sort documents based on the value. So what I was planning to do is create a virtual column (for now lets call it "score") which is set to the average of the two numbers. But the problem is, there is a different model for comments where each comment holds reference to its story. So I have already implemented a virtual column that sets "commentCount":

  StorySchema.virtual('commentCount', {
    ref: 'Comment',
    localField: '_id',
    foreignField: 'story',
    count: true,
  });

Now my query is, how can I use this virtual column to calculate my "score" virtual column.

For more details, I previously tried using aggregation and was successful. But I have to use mongoose-paginate-v2 library that seems to not support aggregation. If you know a better approach than what I am doing, feel free to suggest me.

The main point is I must be able to gather commentCount form another model, and take its and viewCount's average and sort doucments based on that average.

0 Answers
Related