Search⌘ K
AI Features

Fetch All User Reviews

Explore how to implement a controller and route in Go that fetches all movie reviews made by a specific user from MongoDB. This lesson guides you through setting up the endpoint, integrating authentication, and testing the functionality with real user data and curl commands.

Setting up the controller

Assume that the user has a profile page where they can view all of their prior movie reviews. Such a page would require an endpoint to retrieve all the reviews where the reviewer_id matches.

// Allow a user view all their Reviews
func AllUserReviews() gin.HandlerFunc {
return func(c *gin.Context) {
var searchreviews []models.Reviews
reviewId := c.Param("reviewer_id")
//defer cancel()
i,erro:= strconv.Atoi(reviewId)
if erro != nil {
// Handle error
}
if reviewId == "" {
log.Println("No reviewer id passed")
c.Header("Content-Type", "application/json")
c.JSON(http.StatusNotFound, gin.H{"Error": "Invalid Search Index"})
c.Abort()
return
}
var ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
defer cancel()
searchquerydb, err := reviewCollection.Find(ctx, bson.M{"reviewer_id":i})
if err != nil {
c.IndentedJSON(404, "something went wrong in fetching the dbquery")
return
}
err = searchquerydb.All(ctx, &searchreviews)
if err != nil {
log.Println(err)
c.IndentedJSON(400, "invalid")
return
}
defer searchquerydb.Close(ctx)
if err := searchquerydb.Err(); err != nil {
log.Println(err)
c.IndentedJSON(400, "invalid request")
return
}
defer cancel()
c.IndentedJSON(200, searchreviews)
}
}
The reviewControllers.go file
...