Go MongoDB driver connects successfully to database but won't retrieve anything

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:

  1. It does not panic when providing a non existing database name client.Database("NON_EXISTING_DB_NAME")
  2. Copy-pasting the same uri to a nodejs project works perfectly.
  3. Changing the username and password fails the connection so I asume the credentials are correct.
  4. This exact code was working yesterday.

Any help or where should I start debugging will be appreciated. Thanks!

Upvotes: 3

Views: 806

Answers (1)

As stated by @Zeke Lu, the filter cannot be nil. A bson.D{} should be used then providing an empty filter.

Upvotes: 0

Related Questions