Home > Software engineering >  How to handle null value in golang?
How to handle null value in golang?

Time:01-27

User model

type UserExample struct {
    Id       primitive.ObjectID `json:"id,omitempty"`
    Name     string             `json:"name,omitempty"`
    Location string             `json:"location,omitempty"`
    Title    string             `json:"title,omitempty"`
}

Update User

func UpdateUserExample() gin.HandlerFunc {
    return func(c *gin.Context) {
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        userId := c.Param("userId")
        var user models.UserExample
        defer cancel()
        objId, _ := primitive.ObjectIDFromHex(userId)

        //Validate the request body
        if err := c.BindJSON(&user); err != nil {
            c.JSON(http.StatusBadRequest, responses.UserResponseExample{
                Status:  http.StatusBadRequest,
                Message: "Error",
                Data: map[string]interface{}{
                    "data": err.Error()},
            })
        }

        update := bson.M{
            "name":     user.Name,
            "location": user.Location,
            "title":    user.Title,
        }
        result, err := userCollectionExample.UpdateOne(ctx, bson.M{
            "id": objId,
        }, bson.M{
            "$set": update,
        })
        if err != nil {
            c.JSON(http.StatusInternalServerError, responses.UserResponseExample{
                Status:  http.StatusInternalServerError,
                Message: "Error",
                Data: map[string]interface{}{
                    "data": err.Error(),
                }})
            return
        }

        //Get Update UserExample Detail
        var updateUser models.UserExample
        if result.MatchedCount == 1 {
            err := userCollectionExample.FindOne(ctx, bson.M{
                "id": objId,
            }).Decode(&updateUser)
            if err != nil {
                c.JSON(http.StatusInternalServerError, responses.UserResponseExample{
                    Status:  http.StatusInternalServerError,
                    Message: "Error",
                    Data: map[string]interface{}{
                        "data": err.Error(),
                    }})
                return
            }
        }
        c.JSON(http.StatusOK, responses.UserResponseExample{
            Status:  http.StatusOK,
            Message: "Success",
            Data: map[string]interface{}{
                "data": updateUser,
            },
        })
    }
}

i have try update data via postman, but if value == null will be delete from collection

In this case, i want Update Title of the User, before update all data already exist

Postman

{
    "title": "User One"
}

its working to change title in collection. but, for other data (name and location)has gone

"data": {
            "id": "63d2ac86aeb9d78d3d5daf21",
            "title": "User One",
        }

so, how to handle null value from request body?

i just want change title for this case

CodePudding user response:

Usually, such partial updates are handled using a structure that looks like this:

type UserUpdateRequest struct {
    Id       primitive.ObjectId `json:"id,omitempty"`
    Name     *string             `json:"name,omitempty"`
    Location *string             `json:"location,omitempty"`
    Title    *string             `json:"title,omitempty"`
}

Note the pointers. This way, the API caller can send non-nil values for the field it wants to update. It can also use an empty string to set the field values to empty.

Then on the database side, you have to create an update statement:

updateFields:=bson.M{}
if request.Name!=nil {
   updateFields["name"]=*request.Name
}
if request.Location!=nil {
   updateFields["location"]=*request.Location
}
// etc.
update:=bson.M{"$set":updateFields}

Then use the update to update the database record.

  • Related