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

我写了一个更新函数,但是多次执行会报错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


跃然一笑
浏览 207回答 5
5回答

慕仙森

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

不负相思意

尝试更改上下文超时,例如 30 秒ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)

慕雪6442864

尝试使用ctx := context.Background()代替,ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)当我尝试使用 MongoDB 服务器开发 REST 后端时,这解决了我的问题

智慧大石

您的 URI 错误,因为您使用的是 docker。如果您的 mongoDB 容器调用mongoContainer,您应该:client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://mongoContainer"))

吃鸡游戏

在 GoLand 中调试时,如果您有一个断点并且程序等待,然后您继续并收到此错误,有时会发生这种情况。如果删除断点并再次运行该程序,它就会起作用。至少我的情况就是这样。
打开App,查看更多内容
随时随地看视频慕课网APP