dsjfrkvn818747 2016-05-20 11:34
浏览 50
已采纳

Golang + Mgo-如何更新数据库文件?

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){
                }
            });
  • 写回答

1条回答 默认 最新

  • dragonmeng2002 2016-05-20 11:41
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?