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 關注
- 207 瀏覽
添加回答
舉報