问题描述
我想将我的 laravel 5.7 应用程序(我使用 3.4 版本的 jenssegers/mongodb)与 atlas 中的 mongodb 连接,我在 localhost 中尝试过(我没有安装 mongo 扩展),一切正常,但是使用 atlas 时出现错误留言:
无法解析 MongoDB URI: 'mongodb://root%3Acluster0.xxx.mongodb.net%3A27017%2Fhddatabase%3FretryWrites%3Dtrue%26w%3Dmajority'。 URI 中的主机字符串无效。
我的环境文件:
DB_CONNECTION=mongodb
DB_DSN="mongodb://root:[email protected]:27017/hddatabase?retryWrites=true&w=majority"
DB_DATABASE=hddatabase
我的数据库配置:
'mongodb' => [
'driver' => 'mongodb','dsn' => env('DB_DSN'),'database' => env('DB_DATABASE'),],
解决方法
TL;DR:网址错误。 “+srv”部分丢失。 请从 Atlas Connection Wizard 复制 url:
您可以从集群视图中打开连接:
详情
Atlas 默认提供 3 个 mongo db 实例的副本集集群。您的本地数据库是独立的。
连接mongodb有2种格式:
-
mongodb://
是传统的,它要求副本集的所有成员都明确存在于 url 中。例如:mongodb://<username>:<password>@cluster0-shard-00-00.xxx.mongodb.net:27017,cluster0-shard-00-01.xxx.mongodb.net:27017,cluster0-shard-00-02.xxx.mongodb.net:27017/<dbname>?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority
-
mongodb+srv://
是“srv”格式,它允许驱动程序从 mongodb 本身检索副本集配置,因此 url 简单得多:mongodb+srv://<username>:<password>@cluster0.xxx.mongodb.net/<dbname>?retryWrites=true&w=majority
您使用的是较新的格式和旧架构,因此驱动程序会抱怨。
作为旁注,建议使用 https://github.com/jenssegers/laravel-mongodb#configuration 中记录的配置选项 username
和 password
,而不是在 url 中传递它们。 URL 格式需要密码中的 @
、/
等特殊字符进行转义,这会不必要地使凭据管理复杂化。
试试这个 DNS 吧:
mongodb://root:[email protected]:27017
即使使用 'srv' 格式,我也遇到同样的错误,问题是我使用的是 jenssegers/mongodb 的 3.4.0 版,我升级到 3.4.6 版并使用了 'srv' 格式现在问题解决了!