MongoDB 与 golang 错误 "no reachable servers"

标签 mongodb go mgo

我刚刚在 youtube( https://youtu.be/GwQ1hvuSNJA ) 上遵循了本教程。 但是在 go run main.go 之后我收到错误“noreachableservers” 我怎样才能弄清楚?我应该将 localhost 更改为 mongodb uri 吗? 下面是源代码。

var rnd *renderer.Render
var db *mgo.Database

const (
    hostName       string = "localhost"
    dbName         string = "demo_todo"
    collectionName string = "todo"
    port           string = ":3000"
)

func init() {
    rnd = renderer.New()
    sess, err := mgo.Dial(hostName)
    checkErr(err)
    sess.SetMode(mgo.Monotonic, true)
    db = sess.DB(dbName)
}

func main() {
    stopChan := make(chan os.Signal, 1)
    signal.Notify(stopChan, os.Interrupt)

    r := chi.NewRouter()
    r.Use(middleware.Logger)
    r.Get("/", homeHandler)

    r.Mount("/todo", todoHandlers())

    srv := &http.Server{
        Addr:         port,
        Handler:      r,
        ReadTimeout:  60 * time.Second,
        WriteTimeout: 60 * time.Second,
        IdleTimeout:  60 * time.Second,
    }

    go func() {
        log.Println("Listening on port ", port)
        if err := srv.ListenAndServe(); err != nil {
            log.Printf("listen: %s\n", err)
        }
    }()
}

最佳答案

附注:github.com/globalsign/mgo早已无人维护(已经四年多了)。请使用 official MongoDB Go driver .


您可以将 MongoDB URI 传递给 mgo.Dial() ,不仅仅是主机名。您未指定的部分将使用与您的实际值不匹配的默认值。因此请提供完整的 URI。

它的语法为:

[mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options]

For example, it may be as simple as:

localhost

Or more involved like:

mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb

If the port number is not provided for a server, it defaults to 27017.

The username and password provided in the URL will be used to authenticate into the database named after the slash at the end of the host names, or into the "admin" database if none is provided. The authentication information will persist in sessions obtained through the New method as well.

所以这样做:

uri := fmt.Sprintf("mongodb://%s:%s/%s", hostName, port, dbName)
sess, err := mgo.Dial(uri)

关于MongoDB 与 golang 错误 "no reachable servers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73541056/

相关文章:

node.js - Mongodb native 驱动程序 toArray() on limit(1)?

go - 是否有扩展 ipv6 地址的内置功能?

mongodb - 如何在golang中向mongodb插入一个json对象数组

mongodb - 如何在mgo框架中使用mongodb 3.6的数组过滤器?

mongodb - 如何在mgo(Go)中使用接口(interface)类型作为模型?

java - Morphia 泛型 - 不可能吗?

mongodb - 如何从 mongodb 获取唯一记录?

mongodb - Mongoid:检查现有文档/嵌入文档

go - Go语言一个包的所有方法返回的错误列表

go - 使用接口(interface)获取结构的值