Update a Movie
Learn how to update the existing data in the database.
We'll cover the following...
Setting up the controller
If we want to change a specific detail in a movie, we need to create an update endpoint. This endpoint will accept the movie_id
of the movie that we want to update as well as the parameters to be changed. It will be a secured route, and only administrators can change the context of movies.
// Update a moviefunc UpdateMovie() gin.HandlerFunc {return func(c *gin.Context) {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)movieId := c.Param("movie_id")var movie models.Moviedefer cancel()objId, _ := primitive.ObjectIDFromHex(movieId)if err := c.BindJSON(&movie); err != nil {c.JSON(http.StatusBadRequest, gin.H{"Status": http.StatusBadRequest,"Message": "error","Data": map[string]interface{}{"data": err.Error()}})return}if validationError := validate.Struct(&movie); validationError != nil {c.JSON(http.StatusBadRequest, gin.H{"Status": http.StatusBadRequest,"Message": "error","Data": map[string]interface{}{"data": validationError.Error()}})return}update := bson.M{"name": movie.Name,"topic": movie.Topic,"genre_id": movie.Genre_id,"movie_url": movie.Movie_URL}filterByID := bson.M{"_id": bson.M{"$eq": objId}}result, err := movieCollection.UpdateOne(ctx, filterByID, bson.M{"$set": update})if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"Status": http.StatusInternalServerError,"Message": "error","Data": map[string]interface{}{"data": err.Error()}})return}var updatedMovie models.Movieif result.MatchedCount == 1 {err := movieCollection.FindOne(ctx, filterByID).Decode(&updatedMovie)if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"Status": http.StatusInternalServerError,"Message": "error","Data": map[string]interface{}{"data": err.Error()}})return}}c.JSON(http.StatusOK, gin.H{"Status": http.StatusOK,"Message": "movie updated successfully!","Data": updatedMovie})}}
The movieController.go file
...
Access this course and 1400+ top-rated courses and projects.