Fetch All Genres

Learn how to implement a controller that retrieves all records from the MongoDB database.

Fetching all the genres in a collection

Consider a scenario in which the administrator has created up to five genres and wants to view them, or a scenario in which one of the users logs in and wants to browse through the various genres. We must submit a request to the database for all the genres saved in the genre collection in order for both individuals to successfully view all the genres. We perform a quick request to get all the data using MongoDB’s “Read” feature. The authentication middleware protects the route as usual, and only authorized users are able to access it. There are no search parameters included in the simple GET request.

Setting up the controller

In the genreCollections.go file, we create a GetGenres() function. The genreCollection.aggregate operation fetches all the genres from the database. We import the strconv package as well. The job of this package is to convert one data type to another. Right after we create the GetGenres() function, we’ll add the code below. The job of this function is to search the database and return all the genres in the genre collection as well as the total count.

Get hands-on with 1200+ tech skills courses.