为了账号安全,请及时绑定邮箱和手机立即绑定

Golang 报告 MongoDB“超出了上下文截止日期”

Golang 报告 MongoDB“超出了上下文截止日期”

Go
跃然一笑 2023-06-26 18:01:21
我写了一个更新函数,但是多次执行会报错context deadline exceeded。我的功能:func Update(link string, m bson.M) {    configInfo := config.Config()    // client := GetInstance().client    // ctx := GetInstance().ctx    client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)    defer cancel()    err := client.Connect(ctx)    if err != nil {        fmt.Print("connect error!")        fmt.Println(err)    }    db := client.Database("test")    lianjia := db.Collection("test")    _, err = lianjia.UpdateOne(ctx, bson.M{"Link": link}, bson.M{"$set": m})    if err != nil {        fmt.Print("update error!")        fmt.Println(err)    }}输出:update error!context deadline exceeded
查看完整描述

5 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

更改 mongodb://localhost:27017  mongodb://127.0.0.1:27017/



查看完整回答
反对 回复 2023-06-26
?
不负相思意

TA贡献1777条经验 获得超10个赞

尝试更改上下文超时,例如 30 秒

ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)


查看完整回答
反对 回复 2023-06-26
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

尝试使用

ctx := context.Background()

代替,

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)

当我尝试使用 MongoDB 服务器开发 REST 后端时,这解决了我的问题


查看完整回答
反对 回复 2023-06-26
?
智慧大石

TA贡献1946条经验 获得超3个赞

您的 URI 错误,因为您使用的是 docker。

如果您的 mongoDB 容器调用mongoContainer,您应该:

client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://mongoContainer"))


查看完整回答
反对 回复 2023-06-26
?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

在 GoLand 中调试时,如果您有一个断点并且程序等待,然后您继续并收到此错误,有时会发生这种情况。如果删除断点并再次运行该程序,它就会起作用。至少我的情况就是这样。



查看完整回答
反对 回复 2023-06-26
  • 5 回答
  • 0 关注
  • 199 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信