登录
首页 >  Golang >  Go问答

MongoDB Atlas 未与我的 golang 应用程序连接

来源:stackoverflow

时间:2024-03-31 18:45:29 327浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《MongoDB Atlas 未与我的 golang 应用程序连接》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我是 golang 和 mongodb 的新手,我一直在关注 mongodb 的官方博客来开始使用 mongo-db 驱动程序,但由于某种原因我无法连接到我的 mongodb 这是代码,错误是“超出上下文截止日期”,提前谢谢

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    // "go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() {
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://chandru:@cluster0-9jkaf.mongodb.net/test?retryWrites=true&w=majority"))
    if err != nil {
        log.Fatal(err)
    }
    ctx, _ := context.WithTimeout(context.Background(), 20*time.Second)
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect(ctx)
    databases, err := client.ListDatabaseNames(ctx, bson.M{})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(databases)
}

解决方案


一个可能的原因是您没有使用 MongoDB Atlas 将您的 IP 列入白名单 请参考以下指南:https://docs.atlas.mongodb.com/security-whitelist/#view-whitelist-entries

请记住,如果您从本地计算机进行连接,您的 IP 地址可能会发生变化。您可以从 ISP 获取静态 IP 地址或通过另一台计算机连接。

您也可以输入0.0.0.0/0以允许任何IP访问,但这当然不太安全。

以上就是《MongoDB Atlas 未与我的 golang 应用程序连接》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>