Bulk write failed due to previous MongoDB\Driver\Exception\AuthenticationException: Authentication failed.
这里thinkphp6内置的think-orm
已经包含mongo连接了,所以不用单独安装think-mongo
(安装后类会冲突导致报错)
1.添加.env配置文件中的配置
[mongo]
HOSTNAME = "127.0.0.1"
AUTH_DATABASE = admin
DATABASE = test
USERNAME = root
PASSWORD = root
HOSTPORT = 27017
CHARSET = utf8
DEBUG = true
2.修改配置文件database.php
添加mongo配置
'mongo' => [
'type' => 'mongo',
'hostname' => env('mongo.hostname', '127.0.0.1'),
'database' => env('mongo.database', ''),//操作数据库
'auth_database' => env('mongo.auth_database', env('mongo.database', '')),//授权数据库
'username' => env('mongo.username', 'root'),
'password' => env('mongo.password', ''),
'hostport' => env('mongo.hostport', '27017'),
'debug' => env('mongo.debug', true),
'dsn' => env('mongo.dsn', ""),
'schema_cache_path' => app()->getRuntimePath() . 'schema' . DIRECTORY_SEPARATOR,
],
3.修改tp框架底层vendor/topthink/think-orm/src/db/connector/Mongo.php
第100行,将以下代码替换
/**
* 架构函数 读取数据库配置信息
* @access public
* @param array $config 数据库配置数组
*/
public function __construct(array $config = [])
{
if (!empty($config)) {
$this->config = array_merge($this->config, $config);
}
/**
* TinyMeng update start
* DateTime: 2020-04-20 11:15
*/
if(!empty($this->config['username'])){
$this->config['params']['username'] = $this->config['username'];
}
if(!empty($this->config['password'])){
$this->config['params']['password'] = $this->config['password'];
}
if(!empty($this->config['auth_database'])){
$this->config['params']['db'] = $this->config['auth_database'];
}
/** TinyMeng update start */
// 创建Builder对象
$class = $this->getBuilderClass();
$this->builder = new $class($this);
}