我正在尝试从 go 连接到 mongodb。我的乐趣是让我收集收藏
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
}
调用代码:
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: %v\n", err)
}
var results []bson.D
err = cursor.All(context.TODO(), &results)
if err != nil {
fmt.Printf("err in cursor: %v\n", err)
}
for _, result := range results {
fmt.Printf("result: %v\n", result)
}
}
当我调用它并尝试使用我得到的集合时
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]
任何帮助表示赞赏。
在你的代码中
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
这将在代码到达 dbConnection 函数末尾后调用。 所以它会断开与 mongodb 的连接。