Home >Backend Development >Golang >MongoDB GO driver overwrites existing data

MongoDB GO driver overwrites existing data

WBOY
WBOYforward
2024-02-08 23:00:35934browse

MongoDB GO 驱动程序覆盖现有数据

php Editor Banana brings an introduction to the MongoDB GO driver’s new coverage of existing data. As a popular NoSQL database, MongoDB is gaining popularity among developers. This new driver provides a flexible and efficient way to manipulate data in MongoDB. It supports a variety of query and update operations while also providing advanced features such as transaction processing and data aggregation. By using this driver, developers can easily interact with MongoDB in GO projects, enabling rapid development and high performance. Whether it's a new or existing project, this driver provides developers with a better data manipulation experience. Whether you are a beginner or an experienced developer, this driver will be your best choice.

Question content

I am using go-fiber and using the mongodb mongodb go driver. I only want to update the fields given by the body. But it is overwriting the data.

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)

}

If this is how the driver works, please tell me a better way to update the documentation.

Workaround

$set operator will cover all fields you specify, so you must selectively construct the update statement:

fields:=bson.m{}
if body.name!="" {
   fields["name"]=body.name
}
...
update:=bson.m{"$set":fields}

There are some shortcuts you can use:

fields:=bson.M{}
add:=func(key,value string) {
   if value!="" {
      fields[key]=value
   }
}
add("name",body.Name)
add("userName",body.UserName)

The above is the detailed content of MongoDB GO driver overwrites existing data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete