Here's a little optional improvement you could add to the code.
At the moment, we're always fetching all (!) comments - no matter for which event we sent a GET request.
We might just want to fetch the comments that belong to that specific event instead.
You can adjust the code to ensure that only the comments for a specific event (by event id) are fetched.
For this, you need to change the code in two places.
1) In helpers/db-util.js, add an extra, optional parameter (with a default value) to the getAllDocuments() parameter list:
export async function getAllDocuments(client, collection, sort) { ... }becomes
export async function getAllDocuments(client, collection, sort, filter = {}) { ... }The filter = {} parameter allows us to set a filter for finding documents. The default (an empty object: {}) ensures that NO filter is applied (i.e. we get ALL documents).
To use this filter, also change the find() method inside of the getAllDocuments() function:
const documents = await db
.collection(collection)
.find(filter) // this changed - we use the "filter" parameter!
.sort(sort)
.toArray();2) In pages/api/comments/[eventId].js, pass a value for the filter argument:
Inside of the req.method === 'GET' block, change the way you call getAllDocuments().
const documents = await getAllDocuments(
client,
'comments',
{ _id: -1 },
);should become
const documents = await getAllDocuments(
client,
'comments',
{ _id: -1 },
{ eventId: eventId } // this was added!
);By adding these changes, you ensure that you only fetch the comments that really belong to a specific event.