繁体   English   中英

如何在 golang 中处理 null 值?

[英]How to handle null value in golang?

用户 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"`
}

更新用户

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,
            },
        })
    }
}

我尝试通过 postman 更新数据,但如果值 == null 将从集合中删除

在这种情况下,我想更新用户的标题,在更新所有数据之前已经存在

Postman

{
    "title": "User One"
}

它正在努力改变收藏中的标题。 但是,对于其他数据(名称和位置)已经消失

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

那么,如何处理请求体中的 null 值呢?

我只想更改此案例的标题

通常,此类部分更新是使用如下结构处理的:

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

注意指针。 这样,API 调用者可以为它想要更新的字段发送非零值。 它还可以使用空字符串将字段值设置为空。

然后在数据库端,你必须创建一个更新语句:

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}

然后使用update更新数据库记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM