MongoDB Atlas not connecting with my golang App

Viewed 425

I'm new to golang and MongoDB i've been following the official blog of mongoDb for getting started with mongo-db driver for go, and i'm not able to connect to my mongodb for some reason here is the code ,the error is "context deadline exceeded", thnx in advance

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    // "go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() {
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://chandru:<Heregoesmypassword>@cluster0-9jkaf.mongodb.net/test?retryWrites=true&w=majority"))
    if err != nil {
        log.Fatal(err)
    }
    ctx, _ := context.WithTimeout(context.Background(), 20*time.Second)
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect(ctx)
    databases, err := client.ListDatabaseNames(ctx, bson.M{})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(databases)
}
1 Answers

One possible cause is that you have not whitelisted your IP with MongoDB Atlas Please refer to the following guide: https://docs.atlas.mongodb.com/security-whitelist/#view-whitelist-entries

Keep in mind that if you connect from your local machine, your IP address might change. You can get a static IP address from your ISP or connect to through another machine.

You can also enter 0.0.0.0/0 to allow access from any IP, but this is of course less secure.

Related