1

I have a problem with mongodb website. Below i send image with my issue. I built project in Golang where i want to connect with mongodb and if i tried I got error

server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: localhost:27017, Type: Unknown, Last error: dial tcp [::1]:27017: connect: connection refused }, ] }

Here I have code where i trying to connect with mongo client


func Connect() *DB {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        log.Fatal(err)
    }
    err = client.Connect(ctx)
    return &DB{
        client: client,
    }

}

Error on site enter image description here

1 Answers1

0

Not sure to which MongoDB you are trying to connect. In your code example, the DB is on your local machine. Your code is missing the DB credentials.

You can try the following code to connect to the DB and verify your connectivity:

client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://admin:password@localhost:27017"))
if err != nil {
    log.Fatal(err)
}
if err = client.Ping(context.TODO(), readpref.Primary()); err != nil {
    log.Fatal(err)
}
log.Println("Connected to MongoDB") 
Ronen
  • 189
  • 3