FindOneAndUpdate函数不会更新数据库

时间:2019-09-11 19:19:07

标签: mongodb rest go crud

我正在使用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

1 个答案:

答案 0 :(得分:0)

因此,您似乎正在尝试将其解码为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/