亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MongoDB Golang Driver 僅提供更新字段值不為空

MongoDB Golang Driver 僅提供更新字段值不為空

Go
弒天下 2022-10-31 17:23:46
我想創建一個函數來通過它的 id 更新 MongoDB 中的特定文檔,但只有在新提供的值不是 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    }
查看完整描述

1 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

您必須動態構建更新子句:


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

}


查看完整回答
反對 回復 2022-10-31
  • 1 回答
  • 0 關注
  • 204 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號