I'm trying to insert a document into mongodb, but despite successfully connecting to mongo, I still get the following error:
http: panic serving 172.27.0.8:40176: runtime error: invalid memory address or nil pointer dereference
My main.go which is initializing the database connection looks like this
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 }
In a separate file models.go, I try to insert data into the database like this:
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 }
Can anyone spot what I'm doing wrong?
Since the error is generic (e.g. wrong line number not provided), I'll share a possible solution that might help you figure out the problem. Let me share the code first.
main.go
Filepackage 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) } }
For demonstration, I put all the logic in one file. In this file I performed the following steps:
logentry
instance into the mycollection
collection. mycollection
collection. The last thing to mention is the docker command I use to run the container:
docker run -d -p 27017:27017 --name mymongo -e mongo_initdb_root_username=root -e mongo_initdb_root_password=root mongo:latest
If you stick with my solution, you should be able to insert the document without any problems. If not, please let me know and I'll try to help you!
The above is the detailed content of Golang cannot create document in MongoDB. For more information, please follow other related articles on the PHP Chinese website!