drjk87189 2019-09-11 19:19
浏览 231

FindOneAndUpdate函数不会更新数据库

I'm creating a REST api using Go and Mongo. I am still fairly new to the languages. So basically, I call this function to update existing data in a database. It is not actually updating anything in the database.

func UpdateCompanyEndpoint(response http.ResponseWriter, request *http.Request) {
    response.Header().Set("content-type", "application/json")
    params := mux.Vars(request)
    name, _ := params["name"]
    var company Company
    _ = json.NewDecoder(request.Body).Decode(&company)
    filter := bson.D{{"name", name}}
    fmt.Println(name)
    update := bson.D{{"$set", bson.D{{"application", company.Application}}}}
    collection := client.Database("RESTful").Collection("companies")
    doc := collection.FindOneAndUpdate(
        context.Background(),
        filter,
        update,
        nil)
    fmt.Println(doc)
}

The database looks like this:

[
    {
        "name": "Test1",
        "application": "Test1"
    },
    {
        "name": "Test2",
        "application": "Test2"
    },
    {
        "name": "Test3",
        "application": "Test3"
    }
]

I call the put method on http://localhost:8080/update/Test2 with:

{
    "name": "Test2",
    "application": "Test2update"
}

However, it does not update anything in the database. Here is the code: https://github.com/jasonkim615/internship-db/blob/master/main.go

  • 写回答

1条回答 默认 最新

  • dongli8722 2019-09-11 22:07
    关注

    So it appears you are trying to decode into the Company . I can not see the structure of Company, but the data it holds may help answer your question. create structs to mimic your json structure and then decode your json. Here is an example (using UnMarshall, due to using static string in example) for stream data with *Writer Type Use Decode.

        package main 
    
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type person struct {
        Name  string `json:"Name"`
        Age   int    `json:"Age"`
        Alive bool   `json:"Alive"`
    }
    
    func main(){
        JSON:= `[{"Name":"somename","Age":29,"Alive":true},{"Name":"Tyrone","Age":39,"Alive":true}]`
        //First Must Convert to slice of bytes
        JSONBYTE:= []byte(JSON)
        //Made New Slice To Hold Data From JSON 
       var people  []person
        //Converting JSON to Struct must give *Address
          err := json.Unmarshal(JSONBYTE, &people)
      //If 
        if err != nil {
            fmt.Println(err)
        }
    
            for _, i := range people {
                fmt.Printf("Person Name: %v
    ", i.Name)
            }
        //Save To DB example only
        // _, err = db.Collection(COLLECTION).InsertMany(context.Background(), people)
        //  if err != nil {
        //   log.Fatal(err)
           }
    

    Here is an example using Decoder From Parse JSON HTTP response using golang

        package main
    
    import (
        "bytes"
        "encoding/json"
        "fmt"
        "log"
    )
    
    type Example struct {
        Type    string   `json:"type,omitempty"`
        Subsets []Subset `json:"subsets,omitempty"`
    }
    
    type Subset struct {
        Addresses []Address `json:"addresses,omitempty"`
    }
    
    type Address struct {
        IP string `json:"IP,omitempty"`
    }
        func main() {
    
        m := []byte(`{"type":"example","data": {"name": "abc","labels": {"key": "value"}},"subsets": [{"addresses": [{"ip": "192.168.103.178"}],"ports": [{"port": 80}]}]}`)
    
        r := bytes.NewReader(m)
        decoder := json.NewDecoder(r)
    
        val := &Example{}
        err := decoder.Decode(val)
    
        if err != nil {
            log.Fatal(err)
        }
    
        // If you want to read a response body
        // decoder := json.NewDecoder(res.Body)
        // err := decoder.Decode(val)
    
        // Subsets is a slice so you must loop over it
        for _, s := range val.Subsets {
            // within Subsets, address is also a slice
            // then you can access each IP from type Address
            for _, a := range s.Addresses {
                fmt.Println(a.IP)
            }
        }
    
    }
    //The output would be: 192.168.103.178
    

    Also Really neat tool for turning JSON to Struct https://mholt.github.io/json-to-go/

    评论

报告相同问题?

悬赏问题

  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?