问题一: 在ApplyUR函数中填写参数时,头几次填写为空时还报错,调试一久返回client不为空,err为空(至今很迷惑)
var mgoDB *mongo.Database
func Connect() {
ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)
opt := options.Client().ApplyURI(viper.GetString("mongo.addrs"))
if client, err := mongo.Connect(ctx, opt); err != nil {
panic(err)
} else {
ctx2, _ := context.WithTimeout(context.Background(), 2*time.Second)
err := client.Ping(ctx2, readpref.Primary())
if err != nil {
panic(err)
}
mgoDB = client.Database(viper.GetString("mongo.db"))
}
}
以上代码主要意思是:获取配置中参数连接mongodb然后通过ping来检查是否此client有效
问题二:为什么这么做?(这也是我现在不得已的做法)
由于问题一中url无论填什么它都不返回错误(后来查出问题是因为它默认连接了本地的127.0.0.1:27017 我本身是连接的远端),后来关闭本地服务err还是返回了
后来又碰到mongo的权限的问题,它不会通过连接来返回(connect返回的err)
意思是:无论url填密码登陆还是无密码
登陆都不会抛出错误(我在navicat中看到的是无密码可以连接但是没有库,有密码正常)
mongodb://用户名:密码@地址:27017
也就是说我操作的这个mongo官方包鉴权是方面可能存在不足,于是通过ping操作来判断该连接是否有效