Search code examples
angularjsmongodbgomgo

Golang+mgo - how to update a db document?


I have an angularJS frontend using $resource to send requests using HTTP methods to my Go server. I want to update an existing db entry when I send a PATCH. I need to supply multiple data fields to the GO server. How should the angularJS client send the data, in what format? From the mgo doc I found the code below to update. Is it possible for the Update field to take a Go struct which will be parsed from data received from the client and skip the fields that are empty?

        change := mgo.Change{
            Update:    bson.M{"$inc": bson.M{"n": 1}},
            Upsert:    false,
            Remove:    false,
            ReturnNew: true,
        }
        info, err = col.Find(M{"_id": id}).Apply(change, &doc)
        fmt.Println(doc.N)

My angularjs code where i plan to send the data as a query.

            UpdateOneSchedule.update({bkresources:dbResources},
            function(data){
                //on success
            },
            function(httpResponse){
                //on error
                if(httpResponse.status === 409){
                }
            });

Solution

  • Yes, it's possible. A simple example would be:

    var myStruct struct {
        Name string `json:"name" bson:"name,omitempty"`
        Age  int    `json:"age" bson:"age"`
    }
    

    You parse your data into myStruct and give that same object to update.

    change := mgo.Change{
        Update:    bson.M{"$inc": bson.M{"n": 1}, "$set": bson.M{"name": myStruct.Name}},
        Upsert:    false,
        Remove:    false,
        ReturnNew: true,
    }
    info, err = col.Find(M{"_id": id}).Apply(change, &doc)
    fmt.Println(doc.N)
    

    ,omitempty will work the same way as it works with JSON, meaning, if it's empty it won't get parsed, example:

    myStruct.Name = ""
    myStruct.Age = 23
    col.Insert(myStruct)
    

    This would create the following BSON document:

    {
        id: ObjectId("573da7dddd73171e42a84045"),
        age: 23
    }