2 回答

TA貢獻1842條經驗 獲得超21個贊
我相信您的問題是由變量陰影(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 在嘗試使用它時會崩潰,因為它為零。
有多種方法可以解決此問題,例如在本地范圍內使用不同的變量名稱并將客戶端分配給全局變量:
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
有關 Golang 變量陰影討論的更多信息,請參閱Issue#377 提案

TA貢獻1834條經驗 獲得超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 關注
- 213 瀏覽
添加回答
舉報