Rumah >pembangunan bahagian belakang >Golang >Golang tidak boleh membuat dokumen dalam MongoDB
我正在尝试将文档插入 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
如果您坚持使用我的解决方案,您应该能够毫无问题地插入文档。如果不是这样,请告诉我,我会尽力帮助您!
Atas ialah kandungan terperinci Golang tidak boleh membuat dokumen dalam MongoDB. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!