我正在嘗試將文件插入 mongodb,但儘管成功連接到 mongo,但我仍然收到以下錯誤:
http: panic serving 172.27.0.8:40176: runtime error: invalid memory address or nil pointer dereference
我正在初始化資料庫連接的 main.go 看起來像這樣
func main(){ //connect to mongo mongoclient,err:=connecttomongo() if err!=nil{ log.panic(err) } client=mongoclient //create a context that mongo needs in order to disconnect ctx,_:=context.withtimeout(context.background(), 15*time.second) // ctx,cancel:=context.withtimeout(context.background(), 15*time.second) //defer cancel() //close connection defer func () { if err =client.disconnect(ctx); err!=nil{ panic(err) } }() muxrouter := mux.newrouter().strictslash(true) //specify who's allowed to connect c:=cors.new(cors.options{ allowedorigins: []string{"https://*", "http://*"}, allowedmethods: []string{"get", "post", "put", "delete", "options"}, allowedheaders: []string{"accept", "authorization", "content-type", "x-csrf-token"}, exposedheaders: []string{"link"}, allowcredentials: true, maxage: 300, }) router := addroutes(muxrouter) handler := c.handler(router) log.println("service stratring at o port ",webport) sterr := http.listenandserve(":9090", handler) //uncomment this line when using docker if sterr != nil { log.fatal("error starting http server :: ", err) return } log.println("service started at port ",webport) } func connecttomongo()(*mongo.client,error){ mongousername := os.getenv("mongousername") mongopassword := os.getenv("mongopassword") //create connection options clientoptions:=options.client().applyuri(mongourl) clientoptions.setauth(options.credential{ username: mongousername, password: mongopassword, }) //connect c,err:=mongo.connect(context.todo(),clientoptions) if err!=nil{ log.println("error connecting to mongo",err) return nil,err } log.println("connected to mongo") return c,nil }
在一個單獨的檔案 models.go 中,我嘗試將資料插入資料庫,如下所示:
var client *mongo.Client func Insert(entry LogEntry)error{ log.Printf("Attempting to insert %s", entry) log.Printf("client s %s", client) //db:=client.Database("logs") //log.Printf("database is %s", db) collection:=client.Database("logs").Collection("logsCollection") log.Printf("collection is %s", collection) _,err :=collection.InsertOne(context.TODO(), LogEntry{ Name: entry.Name, Data: entry.Data, CreatedAt: time.Now(), UpdatedAt: time.Now(), }) if err!=nil{ log.Println("Error inserting new record into logs collection",err) return err } log.Println("insert successful") return nil }
有人能發現我做錯了什麼嗎?
由於錯誤是通用的(例如,未提供錯誤的行號),我將分享一個可行的解決方案,也許可以幫助您找出問題所在。我先分享一下程式碼。
main.go
檔案package main import ( "context" "fmt" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type LogEntry struct { Name string Data string CreatedAt time.Time UpdatedAt time.Time } func main() { ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) defer cancel() clientOptions := options.Client().ApplyURI("mongodb://root:root@localhost:27017") mongoClient, err := mongo.Connect(ctx, clientOptions) if err != nil { panic(err) } defer mongoClient.Disconnect(ctx) demoDb := mongoClient.Database("demodb") myCollection := demoDb.Collection("myCollection") // delete documents if _, err := myCollection.DeleteMany(ctx, bson.M{}); err != nil { panic(err) } // insert data insertRes, err := myCollection.InsertOne(ctx, LogEntry{ Name: "lorem ipsum", Data: "lorem ipsum", CreatedAt: time.Now(), UpdatedAt: time.Now(), }) if err != nil { panic(err) } fmt.Println(insertRes.InsertedID) // query data cursor, err := myCollection.Find(ctx, bson.M{}) if err != nil { panic(err) } var logEntries []bson.M if err = cursor.All(ctx, &logEntries); err != nil { panic(err) } for _, v := range logEntries { fmt.Println(v) } }
為了演示,我將所有邏輯放在一個文件中。在此文件中,我執行了以下步驟:
mycollection
集合中插入新的 logentry
實例。 mycollection
集合中的所有項目。 最後要提到的是我用來執行容器的 docker 指令:
docker運行-d -p 27017:27017 --name mymongo -e mongo_initdb_root_username=root -e mongo_initdb_root_password=root mongo:latest
如果您堅持使用我的解決方案,您應該能夠毫無問題地插入文件。如果不是這樣,請告訴我,我會盡力幫助您!
以上是Golang無法在MongoDB中建立文檔的詳細內容。更多資訊請關注PHP中文網其他相關文章!