我寫了一個更新函數,但是多次執行會報錯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貢獻1777條經驗 獲得超10個贊
嘗試更改上下文超時,例如 30 秒
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)

慕雪6442864
TA貢獻1812條經驗 獲得超5個贊
嘗試使用
ctx := context.Background()
代替,
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
當我嘗試使用 MongoDB 服務器開發 REST 后端時,這解決了我的問題

智慧大石
TA貢獻1946條經驗 獲得超3個贊
您的 URI 錯誤,因為您使用的是 docker。
如果您的 mongoDB 容器調用mongoContainer
,您應該:
client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://mongoContainer"))

吃雞游戲
TA貢獻1829條經驗 獲得超7個贊
在 GoLand 中調試時,如果您有一個斷點并且程序等待,然后您繼續并收到此錯誤,有時會發生這種情況。如果刪除斷點并再次運行該程序,它就會起作用。至少我的情況就是這樣。
- 5 回答
- 0 關注
- 438 瀏覽
添加回答
舉報
0/150
提交
取消