【问题标题】:FindOneAndUpdate function does not update the databaseFindOneAndUpdate 函数不更新数据库
【发布时间】:2020-01-13 16:09:49
【问题描述】:

我正在使用 Go 和 Mongo 创建一个 REST api。我对这些语言还是很陌生。所以基本上,我调用这个函数来更新数据库中的现有数据。它实际上并没有更新数据库中的任何内容。

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)
}

数据库如下所示:

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

我在 http://localhost:8080/update/Test2 上调用 put 方法:

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

但是,它不会更新数据库中的任何内容。 这是代码:https://github.com/jasonkim615/internship-db/blob/master/main.go

【问题讨论】:

    标签: mongodb rest go crud


    【解决方案1】:

    看来您正试图解码到 Company 中。我看不到公司的结构,但它所拥有的数据可能有助于回答您的问题。创建结构来模仿您的 json 结构,然后解码您的 json。这是一个例子 (使用 UnMarshall,由于在示例中使用了静态字符串)用于流数据 *写入器类型使用解码。

        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\n", i.Name)
            }
        //Save To DB example only
        // _, err = db.Collection(COLLECTION).InsertMany(context.Background(), people)
        //  if err != nil {
        //   log.Fatal(err)
           }
    

    这是一个使用 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
    

    也是将 JSON 转换为 Struct 的非常巧妙的工具 https://mholt.github.io/json-to-go/

    【讨论】:

    猜你喜欢
    • 2020-07-11
    • 2020-05-29
    • 2019-04-19
    • 2018-07-10
    • 1970-01-01
    • 2019-03-14
    • 2019-05-21
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多