我想創建一個函數來通過它的 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})
}
- 1 回答
- 0 關注
- 204 瀏覽
添加回答
舉報
0/150
提交
取消