Go MongoDB驱动成功连接到数据库,但无法检索任何内容。

huangapple go评论80阅读模式
英文:

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

问题

我正在尝试使用Golang MongoDB官方驱动程序连接到我的Mongo Atlas数据库。问题是连接似乎成功,但客户端无法检索任何内容。我尝试记录ListDatabaseNames()ListCollectionNames(),但它总是返回一个空数组,就像数据库是空的一样。

连接字符串是正确的。我在一个NodeJS项目中使用相同的连接字符串,它正常工作。但是将相同的数据库URI复制粘贴到Go项目中却不起作用。

以下是代码:

// 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)
}

上面的代码直接从MongoDB Atlas复制而来。以下是一些需要注意的事项:

  1. 当提供一个不存在的数据库名称client.Database("NON_EXISTING_DB_NAME")时,它不会引发错误。
  2. 将相同的URI复制粘贴到NodeJS项目中可以正常工作。
  3. 更改用户名和密码会导致连接失败,因此我认为凭据是正确的。
  4. 这段代码昨天还能正常工作。

希望能得到帮助,或者告诉我应该从哪里开始调试。谢谢!

英文:

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(&quot;mongodb+srv://&lt;username&gt;:&lt;password&gt;@my_mongodb_cluster.mongodb.net/?retryWrites=true&amp;w=majority&quot;).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(&quot;MY_DB&quot;).RunCommand(context.TODO(), bson.D{{Key: &quot;ping&quot;, Value: 1}}).Err(); err != nil {
		panic(err)
	}

	log.Println(&quot;Pinged your deployment. You successfully connected to MongoDB!&quot;)

	count, err := client.ListDatabaseNames(context.Background(), nil) // always returns []
	log.Println(count)
	if err != nil {
		log.Fatalln(&quot;Error&quot;, 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(&quot;NON_EXISTING_DB_NAME&quot;)
  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!

答案1

得分: 1

根据 @Zeke Lu 的说法,过滤器不能为空。应该使用 bson.D{} 来提供一个空的过滤器。

英文:

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

huangapple
  • 本文由 发表于 2023年5月21日 18:32:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定