1

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
jkim615
  • 11
  • 2

1 Answers1

0

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\n", 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/

Josh
  • 1,059
  • 10
  • 17
  • Sorry, I'm having trouble understanding what you're saying. So is my issue not in the FindOneAndUpdate call? Here is the link to the code: https://github.com/jasonkim615/internship-db/blob/master/main.go – jkim615 Sep 11 '19 at 22:32