Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use update function of mongo-go-driver using struct

The update function of mongo-go-driver can be called like this.

filter := bson.D{"username", username}
update := bson.D{{"$set",
    bson.D{
        {"name", person.Name},
    },
}}
result, err := collection.UpdateOne(ctx, filter, update)
type Person struct {
    ID       primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
    Username string             `json:"username,omitempty" bson:"username,omitempty"`
    Name     string             `json:"name,omitempty" bson:"name,omitempty"`
}

But, I need to call the update function using the person struct, without mentioning every field of person struct like this.

filter := bson.D{"username", username}
update := bson.D{{"$set", <<how to convert person struct to bson document?>>}}
result, err := collection.UpdateOne(ctx, filter, update)

How can I convert the person struct to bson document?

like image 933
sumedhe Avatar asked Apr 29 '19 13:04

sumedhe


2 Answers

ReplaceOne I think is what you're after:

        // Use it's ID to replace
        filter := bson.M{"_id": existing.ID}
        // Create a replacement object using the existing object
        replacementObj := existing
        replacementObj.SomeFieldToChange = "new-replacement-object"
        updateResult, err := coll.ReplaceOne(context.Background(), filter, replacementObj)
        assertNotErr(t, err)
        assertEquals(t, 1, int(updateResult.ModifiedCount))

A note that ErrNotFound is no longer thrown as it was in mgo - you have to check the Modified/Upserted count.

like image 134
TopherGopher Avatar answered Sep 18 '22 08:09

TopherGopher


You could do something like this:

func Update(person Person) error {
  pByte, err := bson.Marshal(person)
  if err != nil {
    return err
  }

  var update bson.M
  err = bson.Unmarshal(pByte, &update)
  if err != nil {
    return
  }

  // NOTE: filter and ctx(Context) should be already defined
  _, err = collection.UpdateOne(ctx, filter, bson.D{{Key: "$set", Value: update}})
  if err != nil {
    return err
  }
  return nil
}
like image 21
lakex Avatar answered Sep 18 '22 08:09

lakex