I am creating a RESTful API and am in the process of creating an update function. I use FindOneAndUpdate, and it doesn't actually update the database.
I have tried many things, but I'm fairly new to the language so I'm a bit lost.
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)
collection := client.Database("RESTful").Collection("companies")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
filter := bson.D{{"name", name}}
update := bson.D{{"$set", bson.D{{"application", company.Application}}}}
err := collection.FindOneAndUpdate(
ctx,
filter,
update).Decode(&company)
if err == nil {
response.WriteHeader(http.StatusInternalServerError)
return
}
json.NewEncoder(response).Encode(company)
}
[
{
"name": "Test1",
"application": "Test1"
},
{
"name": "Test2",
"application": "Test2"
},
{
"name": "Test3",
"application": "Test3"
}
]
This is the current database. When I call the function, it returns:
{
"name": "Test2",
"application": "Test2update"
}
but the database remains unchanged.