首页  >  文章  >  后端开发  >  Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象

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

WBOY
WBOY转载
2024-02-14 22:40:15954浏览

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

问题内容

我曾经使用 React 和 Nodejs 来实现 todo 应用程序。 React 和 Nodejs 中更新 Mongodb 数据库的切换功能如下代码:

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

我想在Golang中实现切换功能来更新布尔字段,但我得到了对象,以下是golang代码:

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
}

Mongodb 中的结果更新为对象而不是布尔值。我该如何修复以使其更新切换布尔值?

解决方法

传递单个文档(例如 bson.Mbson.D)作为更新文档,字段名称和值将按原样(字面意思)解释。

使用带有更新的聚合管道 a>,您必须传递一个数组作为更新文档,这会触发将其解释为聚合管道。这是唯一的要求。该数组可能是 mongo.Pipeline, bson.A[]bson.D []bson.M 甚至 []any,没关系,它必须是 Go 中的数组或切片。这些元素可以是 bson.Mbson.D 或表示文档的任何其他值。

最简单的解决方案:

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

以上是Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除