Laravel 5.7 mongodb 使用 jenssegers/mongodb 的图集连接问题

Laravel 5.7 mongodb atlas connection problem using jenssegers/mongodb

我想将我的 laravel 5.7 应用程序(我使用 jenssegers/mongodb 的 3.4 版本)与 atlas 中的 mongodb 连接,我在 localhost 中尝试(我安装了 mongo 扩展名),一切正常,但使用 Atlas 我收到一条错误消息:

Failed to parse MongoDB URI: 'mongodb://root%3Acluster0.xxx.mongodb.net%3A27017%2Fhddatabase%3FretryWrites%3Dtrue%26w%3Dmajority'. Invalid host string in URI.

我的环境文件:

DB_CONNECTION=mongodb
DB_DSN="mongodb://root:password@cluster0.xxx.mongodb.net:27017/hddatabase?retryWrites=true&w=majority"
DB_DATABASE=hddatabase

我的数据库配置:

'mongodb' => [
    'driver'   => 'mongodb',
    'dsn' => env('DB_DSN'),
    'database' => env('DB_DATABASE'),
],

也许可以试试这个 DNS :

mongodb://root:password@cluster0.xxx.mongodb.net:27017

TL;DR: url 是错误的。 “+srv”部分丢失。 请从 Atlas 连接向导中复制 url:

您可以从集群视图打开连接:

详情

Atlas 默认提供 3 个 mongo 数据库实例的副本集集群。您的本地数据库是独立的。

有 2 种格式可以连接到 mongodb:

  • 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 中记录的配置选项 usernamepassword 而不是在 url 中传递它们。 URL 格式要求在密码中使用 @/ 等特殊字符进行转义,这会使凭据管理变得不必要地复杂化。

即使使用 'srv' 格式我也会遇到同样的错误,问题是我使用的是 jenssegers/mongodb 的 3.4.0 版,我升级到 3.4.6 版并且使用 'srv' 格式,问题现在已解决!