登录
首页 >  Golang >  Go问答

仅更新非空字段的MongoDB Golang驱动程序

来源:stackoverflow

时间:2024-02-12 09:24:25 460浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《仅更新非空字段的MongoDB Golang驱动程序》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我想创建一个函数来通过 mongodb 的 id 更新特定文档,但仅当新提供的值不是 go 默认值时才更新字段。

这是我存储在 mongodb 中的文档结构:

type user struct {
    id          primitive.objectid `json:"id"                    bson:"_id,omitempty"`
    username    string             `json:"username"              bson:"username"`
    firstname   string             `json:"firstname"             bson:"first_name"`
    lastname    string             `json:"lastname,omitempty"    bson:"last_name,omitempty"`
    email       string             `json:"email"                 bson:"email"`
    password    string             `json:"password,omitempty"    bson:"password"`
    phonenumber string             `json:"phonenumber,omitempty" bson:"phone_number,omitempty"`
    picture     string             `json:"picture,omitempty"     bson:"picture,omitempty"`
    role        role               `json:"role"                  bson:"role"`
}

我的更新函数获取要更新的用户文档的 id 和一个仅包含应更新的字段的用户结构。因此,如果仅更新用户名,则提供的用户结构中的所有其他字段都将具有默认值。

我现在需要首先检查新用户名是否不为空,然后才将其包含在新的更新文档中。

这就是我在 javsacript 中解决它的方法。 go 有类似的解决方案吗?

{
  ...(username && { username: username }),
  ...(email && { email: email }),
  ...(firstname && { firstname: firstname }),
  ...(lastname && { lastname: lastname }),
  ...(phone && { phone: phone }),
  ...(picture && { picture: picture }),
},

这是我的更新功能:

func (us *userQuery) Update(userId string, u datastruct.User) (*datastruct.User, error) {
    userCollection := DB.Collection(datastruct.UserCollectionName)

    ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
    defer cancel()

    _id, err := primitive.ObjectIDFromHex(userId)
    if err != nil {
        return nil, err
    }

    update := bson.D{{
        Key: "$set",
        Value: bson.D{
            {Key: "username", Value: u.Username}, // only include a field if provided value is not the default
            {Key: "firstName", Value: u.FirstName},
            {Key: "lastName", Value: u.LastName},
            {Key: "email", Value: u.Email},
            {Key: "password", Value: u.Password},
            {Key: "phoneNumber", Value: u.PhoneNumber},
            {Key: "picture", Value: u.Picture},
        },
    }}

    var result datastruct.User
    res, err := userCollection.UpdateByID(
        ctx,
        _id,
        update,
    )
    if err != nil {
        return nil, err
    }

    return &result, nil
}

正确答案


您必须动态构建更新子句:

value:=bson.M{}
if len(u.UserName)!=0 {
  value["username"]=u.UserName
}
if len(u.FirstName)!=0 {
  value["firstName"]=u.FirstName
}
...
if len(value)>0 { // Is there anything to update?
  res, err := userCollection.UpdateByID(
          ctx,
          _id,
          bson.M{"$set":value})
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>