go - 使用其他功能的mongodb连接

标签 go

我想从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/

相关文章:

go - 需要在本地调试依赖项

go - Gmail API Pub/Sub 推送不停止

go - 对潜在变量范围(也许是指针)的困惑?不确定

mongodb - 如何在golang中编写bson形式的mongo查询?

git - 去获取 : Git settings are ignored

regex - 将特定的返回查询转换为 mgo

go - 聆听高级 Oracle 队列 (AQ)

email - 如何读取多个文本文件并通过电子邮件发送每个文件的最后一行,重复间隔为 5 秒

unit-testing - 如何测试从请求主体读取错误?

go - 这段带有无缓冲 channel 的代码会导致 Go 中的 goroutine 泄漏吗?