我想创建一个函数来通过它的 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
}
慕尼黑5688855
相关分类