I am trying to connect to mongodb from go. My func for getting me the collection
func dbConnection() *mongo.Collection {
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
opts := options.Client().ApplyURI("mongodb+srv://username:pwd@domain").SetServerAPIOptions(serverAPI)
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
collection := client.Database("testdb").Collection("test")
return collection
}
Calling Code:
func sortByName(colls *mongo.Collection) {
coll := dbConnection()
filter := bson.D{{Key: "name", Value: "joe"}}
opts := options.Find().SetSort(bson.D{{Key: "name", Value: 1}})
cursor, err := coll.Find(context.TODO(), filter, opts)
if err != nil {
fmt.Printf("err in FIND: %vn", err)
}
var results []bson.D
err = cursor.All(context.TODO(), &results)
if err != nil {
fmt.Printf("err in cursor: %vn", err)
}
for _, result := range results {
fmt.Printf("result: %vn", result)
}
}
when I am calling this and trying to use the collection I am getting
err in FIND: client is disconnected
panic: runtime error: invalid memory address or nil pointer dereference
panic: runtime error: invalid memory address or nil pointer dereference
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x48 pc=0xcb7b33b]
Any help appreciated.
2
Answers
In your code
this will call after the code reaches end of dbConnection function.
so it will disconnect from mongodb.
to fix this, manage the MongoDB client’s lifecycle at a higher level in your application. Connect to the MongoDB client when the program starts and disconnect when it finishes.