亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在調用 Execute 之前,插入操作必須具有部署集

在調用 Execute 之前,插入操作必須具有部署集

Go
慕神8447489 2023-08-07 19:06:30
我有一個正在運行 MongoDB 的 AWS 實例。我正在嘗試執行一個小型數據庫操作,當下面包含的文件寫入單個 go 文件中時,該操作似乎可以工作。當我嘗試拆分它時,出現以下錯誤在調用 Execute 之前,插入操作必須具有部署集分割后的文件如下連接.gopackage dbimport (    "context"    "fmt"    "log"    "go.mongodb.org/mongo-driver/mongo"    "go.mongodb.org/mongo-driver/mongo/options")var Client1 mongo.Clientfunc Connect() {    // Set client options    clientOptions := options.Client().ApplyURI("remote_url")    // Connect to MongoDB    Client1, err := mongo.Connect(context.TODO(), clientOptions)    if err != nil {        log.Fatal(err)    }    // Check the connection    err = Client1.Ping(context.TODO(), nil)    if err != nil {        log.Fatal(err)    }    fmt.Println("Connected to MongoDB!")}func main() {    fmt.Println("Connection to MongoDB done.")}主程序package mainimport (    "context"    "fmt"    "log"    "db"    "go.mongodb.org/mongo-driver/bson")// You will be using this Trainer type later in the programtype 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.")}它們被放置在以下結構中/src -> main.go/src -> /db/connect.go
查看完整描述

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 提案


查看完整回答
反對 回復 2023-08-07
?
MMMHUHU

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"


查看完整回答
反對 回復 2023-08-07
  • 2 回答
  • 0 關注
  • 213 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號