Reputation: 2093
I'm trying to connect to my mongo Atlas database using golang mongodb official driver. The problem is that the connection seems successful but the client won't retrieve anything. I tried to log ListDatabaseNames()
and ListCollectionNames()
but it always returns an empty array, like the db was empty.
The connection string is correct. I am using the same one with a NodeJS project and it works just fine. Just copy-pasting the same db uri to a go project doesn't works.
Here is the code:
// Use the SetServerAPIOptions() method to set the Stable API version to 1
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
opts := options.Client().ApplyURI("mongodb+srv://<username>:<password>@my_mongodb_cluster.mongodb.net/?retryWrites=true&w=majority").SetServerAPIOptions(serverAPI)
// Create a new client and connect to the server
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
// Send a ping to confirm a successful connection
if err := client.Database("MY_DB").RunCommand(context.TODO(), bson.D{{Key: "ping", Value: 1}}).Err(); err != nil {
panic(err)
}
log.Println("Pinged your deployment. You successfully connected to MongoDB!")
count, err := client.ListDatabaseNames(context.Background(), nil) // always returns []
log.Println(count)
if err != nil {
log.Fatalln("Error", err)
}
The snippet above is copied straight from mongodb Atlas. Here are some things to have in mind:
client.Database("NON_EXISTING_DB_NAME")
Any help or where should I start debugging will be appreciated. Thanks!
Upvotes: 3
Views: 806
Reputation: 2093
As stated by @Zeke Lu, the filter cannot be nil. A bson.D{}
should be used then providing an empty filter.
Upvotes: 0