I'm creating a simple todo
rest API using golang
and mongodb
. I'm also using the mongo-go-driver library.
Basically, I managed to upload my data to mongodb
and I'm able to retrieve the information, but I encounter some problems when I try to use the findOneAndUpdate
function. I'm able to update my data using findOneAndReplace
, However, I want to update the information using a struct and the findOneAndUpdate
function
Here is my struct:
type Todo struct {
ObjectId string
ID string `json:"ID,omitempty"`
Title string `json:"Title,omitempty" bson:"Title"`
Category string `json:"Category,omitempty" bson:"Category"`
Content string `json:"Content,omitempty" bson:"Content"`
Created string `json:"Creation_time,omitempty" bson:"Creation_time"`
Modified string `json:"Modification_time,omitempty" bson:"Modification_time"`
State string `json:"State,omitempty" bson:"State"`
}
Here is the function that decodes my request body into a struct:
func UpdateTodo (w http.ResponseWriter, r *http.Request){
var todo models.Todo
_ = json.NewDecoder(r.Body).Decode(&todo)
urlTodoId := chi.URLParam(r, "id")
UpdateTodoById(todo, urlTodoId)
}
And finally here is the function that updates the data:
func UpdateTodoById(todo m.Todo, todoId string) interface{}{
var todoUpdated m.Todo
objId, err := objectid.FromHex(todoId)
helpers.PanicErr(err)
filter := bson.NewDocument(bson.EC.ObjectID("_id", objId))
fmt.Println(filter)
err = db.Collection(COLLNAME).FindOneAndUpdate(context.Background(), filter, todo).Decode(&todoUpdated)
fmt.Println(todoUpdated)
helpers.PanicErr(err)
return todoUpdated}
When I send the request I receive an error: update document must contain key beginning with '$
So can anyone help? Is there a way to solve this? and use a struct to update the data find the function findOneAndUpdate
? Or is this driver not developed enough to do that yet?
Thank you.