I used to implement todo application using React and Nodejs. The toggle function in React and Nodejs to update Mongodb database as following code:
const toggleChecked = ({ _id, isChecked }) => {
TasksCollection.update(_id, {
$set: {
isChecked: !isChecked
}
})
};
I would like to implement toggle function in Golang to update boolean field, but I got object instead, the following is golang code:
func updateOneMovie(movieId string) model.Netflix {
id, _ := primitive.ObjectIDFromHex(movieId)
filter := bson.M{"_id": id}
update := bson.M{"$set": bson.M{"watched": bson.M{"$not": "$watched"}}}
var updateResult model.Netflix
result, err := collection.UpdateOne(context.Background(), filter, update)
err = collection.FindOne(context.Background(), filter).Decode(&updateResult)
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
return updateResult
}
The result in Mongodb updates as the object instead of boolean. How can I fix to make it update toggle boolean?
2
Answers
I found the solution, I use Pipeline with bson.D as the following code:
The result, I can update boolean correctly.
Passing a single document (e.g.
bson.M
orbson.D
) as the update document, field names and values will be interpreted as-is (literally).To use aggregation pipelines with updates, you must pass an array as the update document. This is the only requirement. The array may be
mongo.Pipeline
,bson.A
,[]bson.D
,[]bson.M
or even[]any
, it doesn’t matter, it just must be an array or slice in Go. The elements may bebson.M
,bson.D
or any other values representing a document.So the simplest solution: