我想从Go示例中的另一个函数使用mongodb连接
func Conn() {
client, err :=
mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
}
调用该函数。
func main(){
Conn.client//something like this
}
最佳答案
我这样解决
var CNX = Connection()
func Connection() *mongo.Client {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
return client
}
//calll connection
func main() {
collection := db.CNX.Database("tasks").Collection("task")
}
output "Connected to MongoDB!"
关于go - 使用其他功能的mongodb连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118986/