Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang reports "context deadline exceeded" with MongoDB

Tags:

mongodb

go

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
like image 218
Jinnrry Avatar asked Jul 02 '19 09:07

Jinnrry


1 Answers

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

like image 181
Jonathan Cani Avatar answered Nov 12 '22 15:11

Jonathan Cani