Golang and MongoDB - I tried to update toggle boolean to mongodb using golang but got the object

WBOY
Release: 2024-02-14 22:40:15
forward
828 people have browsed it

Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象

Question content

I have used React and Nodejs to implement a todo application. The switching function for updating the Mongodb database in React and Nodejs is as follows:

const toggleChecked = ({ _id, isChecked }) => {
  TasksCollection.update(_id, {
    $set: {
      isChecked: !isChecked
    }
  })
};
Copy after login

I want to implement toggle function in Golang to update boolean field, but I got the object, the following is the 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
}
Copy after login

Results in Mongodb are updated as objects instead of booleans. How can I fix it so that it updates the toggle boolean?

Workaround

Pass a single document (e.g. bson.M or bson.D) as the update document and the field names and values ​​will be as-is ( Literal meaning) explanation.

Using the aggregation pipeline with updates , you must pass an array as the update document, which triggers its interpretation as an aggregation pipeline. 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 must be an array or a slice in Go. These elements can be bson.M, bson.D, or any other value representing the document.

Easiest solution:

filter := bson.M{"_id": id}
update := []any{
    bson.M{"$set": bson.M{"watched": bson.M{"$not": "$watched"}}}
}
Copy after login

The above is the detailed content of Golang and MongoDB - I tried to update toggle boolean to mongodb using golang but got the object. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!