2 回答
TA贡献1796条经验 获得超4个赞
我相信您的问题是由变量阴影(wiki)引起的,并且您正在初始化一个局部变量而不是全局mongo.Client对象,因此引发了您遇到的错误。
它发生在您的connect.go文件中,您在其中定义了两个Client1具有相同名称的不同变量:
一个在全球范围内
另一个在
Connect()调用时被声明+初始化mongo.Connect()
var Client1 mongo.Client // Client1 at global scope
func Connect() {
// Set client options
clientOptions := options.Client().ApplyURI("remote_url")
// Connect to MongoDB
Client1, err := mongo.Connect(context.TODO(), clientOptions) // Client1 at local scope within Connect()
这导致全局范围内的那个永远不会被初始化,所以 main.go 在尝试使用它时会崩溃,因为它是 nil。
有几种方法可以解决这个问题,例如通过在本地范围内为变量使用不同的名称并将客户端分配给全局变量:
var Client1 mongo.Client
func Connect() {
// Set client options
clientOptions := options.Client().ApplyURI("remote_url")
// Connect to MongoDB
Client1Local, err := mongo.Connect(context.TODO(), clientOptions)
Client1 = *Client1Local
或者避免声明局部变量并直接在全局范围内初始化一个:
var Client1 *mongo.Client // Note that now Client1 is of *mongo.Client type
func Connect() {
// Set client options
clientOptions := options.Client().ApplyURI("remote_url")
// Connect to MongoDB
var err error
Client1, err = mongo.Connect(context.TODO(), clientOptions) // Now it's an assignment, not a declaration+assignment anymore
TA贡献1806条经验 获得超8个赞
尝试包含类似,因为您省略了 db 目录,这可能是问题所在
import "db/db"
connect.go 中还有 main(),一个项目应该只有一个主包和 main() 函数。
---------------- Try what is discussed below exactly ------------
好的,这是我的测试设置,其代码目录树与您的类似:
[user@devsetup src]$ tree test
test
├── dbtest
│ └── db
│ └── connect.go
├── main // This is executable file
└── main.go
2 directories, 3 files
在 connect.go 中,我没有改变任何东西,只是删除了上面提到的 main()。确保只使用导出的函数和变量,导出的函数/变量以大写字母开头。在 main.go 中看起来像下面的代码。* 进入 dbtest/db 目录并运行go install命令。然后转到项目目录,即test在这种情况下,并运行go build main.go or go build .
package main
import (
"context"
"fmt"
"log"
"test/dbtest/db"
// "go.mongodb.org/mongo-driver/bson"
)
// You will be using this Trainer type later in the program
type Trainer struct {
Name string
Age int
City string
}
func main() {
db.Connect()
collection := db.Client1.Database("test2").Collection("trainers")
_ = collection
// fmt.Println("Created collection", _)
ash := Trainer{"Ash", 10, "Pallet Town"}
// misty := Trainer{"Misty", 10, "Cerulean City"}
// brock := Trainer{"Brock", 15, "Pewter City"}
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult)
err = db.Client1.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
}
这是我的二进制输出,因为我没有给出任何输入 url,它抛出一个错误。似乎工作。我在 main.go 中注释掉了一个包和一行
[user@devsetup test]$ ./test
20xx/yy/zz aa:bb:cc error parsing uri: scheme must be "mongodb" or "mongodb+srv"
- 2 回答
- 0 关注
- 273 浏览
添加回答
举报
