Implementing data aggregation in the backend
For our backend, we are going to use very similar aggregation pipelines. However, we need to adjust them slightly, as we always want to get the data for a single post only. As such, we will first be using $match
to filter our documents. This also ensures that the aggregation stays fast, even if we have millions of events in our database, because we are first filtering down to all events of a single post!
Defining aggregation service functions
Follow these steps to implement the aggregation functions in the backend:
- Edit
backend/src/services/events.js
and define a new function to get the total number of views for a post. In this case, we can simplify our code by using thecountDocuments
function instead of the aggregate function:export async function getTotalViews(postId) { return { views: await Event.countDocuments({ post: postId, action: 'startView' }), } }
- Next...