Golang reports "context deadline exceeded" with MongoDB

Viewed 14161

I wrote an update function, but multiple executions will give the error context deadline exceeded.

My function:

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)
    }
}

The output:

update error!context deadline exceeded
5 Answers

Change mongodb://localhost:27017 to mongodb://127.0.0.1:27017/

Try using

ctx := context.Background()

Instead of,

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

This solved the problem for my issue when I try to develop a REST Back End with MongoDB server

try changing your context timeout say 30 sec

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

Your URI is wrong, because you were using docker.

If your containers of mongoDB called mongoContainer, you should:

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

This happens sometimes when debugging in GoLand if you have a breakpoint and the program waits then you continue and get this error. If you remove the breakpoint and run the program again it works. At least that's how it was in my case.

Related