我正在使用GO-FIBER和MONGODB MongoDB Go驱动器。我只想更新正文给出的字段。但它正在覆盖数据。


func UpdateOneUser(c *fiber.Ctx) error {
params := c.Params("id")
body := new(models.User)
id, err := primitive.ObjectIDFromHex(params)
if err != nil {
return c.Status(500).SendString("invalid onjectid")
}
if err := c.BodyParser(&body); err != nil {
return c.Status(400).SendString("invalid body")
}
filter := bson.M{"_id": id}
update := bson.M{"$set": bson.M{
"name": body.Name,
"username": body.Username,
"first_name": body.FirstName,
"last_name": body.LastName,
"email": body.Email,
"phone_number": body.PhoneNumber,
"contry": body.Contry,
"age": body.Age,
"child_accounts": body.ChildAccounts,
"groups": body.Groups,
}}
result, err := db.User.UpdateOne(context.Background(), filter, update)
if err != nil {
return c.Status(500).SendString("user not found")
}
fmt.Println(result)
return c.JSON(body)
}如果这是驱动程序的工作方式,那么请告诉我一种更新文档的更好方法。
发布于 2022-12-02 20:51:00
$set运算符将覆盖指定的所有字段,因此必须有选择地构建update语句:
fields:=bson.M{}
if body.Name!="" {
fields["name"]=body.Name
}
...
update:=bson.M{"$set":fields}您可以使用一些快捷方式:
fields:=bson.M{}
add:=func(key,value string) {
if value!="" {
fields[key]=value
}
}
add("name",body.Name)
add("userName",body.UserName)https://stackoverflow.com/questions/74661282
复制相似问题