您现在的位置是:首页 > 博客日记 > Php Php

Thinkphp6使用mongo报密码错误 Authentication failed

2020-04-20 11:33:25 【Php】 人已围观

Bulk write failed due to previous MongoDB\Driver\Exception\AuthenticationException: Authentication failed.

这里thinkphp6内置的think-orm已经包含mongo连接了,所以不用单独安装think-mongo(安装后类会冲突导致报错)

1.添加.env配置文件中的配置

  1. [mongo]
  2. HOSTNAME = "127.0.0.1"
  3. AUTH_DATABASE = admin
  4. DATABASE = test
  5. USERNAME = root
  6. PASSWORD = root
  7. HOSTPORT = 27017
  8. CHARSET = utf8
  9. DEBUG = true

2.修改配置文件database.php 添加mongo配置

  1. 'mongo' => [
  2. 'type' => 'mongo',
  3. 'hostname' => env('mongo.hostname', '127.0.0.1'),
  4. 'database' => env('mongo.database', ''),//操作数据库
  5. 'auth_database' => env('mongo.auth_database', env('mongo.database', '')),//授权数据库
  6. 'username' => env('mongo.username', 'root'),
  7. 'password' => env('mongo.password', ''),
  8. 'hostport' => env('mongo.hostport', '27017'),
  9. 'debug' => env('mongo.debug', true),
  10. 'dsn' => env('mongo.dsn', ""),
  11. 'schema_cache_path' => app()->getRuntimePath() . 'schema' . DIRECTORY_SEPARATOR,
  12. ],

3.修改tp框架底层vendor/topthink/think-orm/src/db/connector/Mongo.php 第100行,将以下代码替换

  1. /**
  2. * 架构函数 读取数据库配置信息
  3. * @access public
  4. * @param array $config 数据库配置数组
  5. */
  6. public function __construct(array $config = [])
  7. {
  8. if (!empty($config)) {
  9. $this->config = array_merge($this->config, $config);
  10. }
  11. /**
  12. * TinyMeng update start
  13. * DateTime: 2020-04-20 11:15
  14. */
  15. if(!empty($this->config['username'])){
  16. $this->config['params']['username'] = $this->config['username'];
  17. }
  18. if(!empty($this->config['password'])){
  19. $this->config['params']['password'] = $this->config['password'];
  20. }
  21. if(!empty($this->config['auth_database'])){
  22. $this->config['params']['db'] = $this->config['auth_database'];
  23. }
  24. /** TinyMeng update start */
  25. // 创建Builder对象
  26. $class = $this->getBuilderClass();
  27. $this->builder = new $class($this);
  28. }


关注TinyMeng博客,更多精彩分享,敬请期待!
 

很赞哦! ()