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 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示