小编的下载路径供参考:
https://windows.php.net/downloads/pecl/releases/mongodb/1.8.1/
thinkphp6 多应用模式链接 mongoDB 开发笔记
(1) 管理员登录mongo(注意:新安装环境默认没有超级用户密码) mongo [库名] -u [用户名] -p 示例,使用 yix 用户登录 db_yixzm 库
mongo db_yixzm -u yix -p
认证用户
db.auth('db_yixzm ','once')
(2) 新增用户并授权
db.createUser( {user: "once",pwd: "once",roles: [ { role: "readWrite", db: "db_yixzm" } ]})
更新用户信息
db.updateUser( "once",{pwd: "once",roles: [ { role: "readWrite", db: "db_yixzm" } ]})
tp6 连接 mongo 开发过程中有几次报错,报错内容及解决方法如下: (1) 报错
No suitable servers found (`serverSelectionTryOnce` set):
原因: 端口不匹配。(.env文件和应用下config目录下的database.php文件都要检查,确保端口没有错误) (2) 报错
Class 'MongoDB\Driver\Query' not found
原因:
MongoDB驱动有问题,多半是因为 php_mongodb.dll 版本不对,或者 php.ini 中的 php_mongodb 扩展没有打开。
分享一个版本查看方法:
composer require mongodb/mongodb
,版本不一致就会报错,告诉你框架真正需要的版本号
(3)
密码中包含!
或者@
字符引起的报错。简单办法是改密码,或者新增用户不要使用包含!
或者@
字符的密码。
(4)
报错:
Authentication failed.
解决: 修改文件
vendor\topthink\think-orm\src\db\connector\Mongo.php
将connect函数替换为以下代码:
/**
* 连接数据库方法
* @access public
* @param array $config 连接参数
* @param integer $linkNum 连接序号
* @return Manager
* @throws InvalidArgumentException
* @throws RuntimeException
*/
public function connect(array $config = [], $linkNum = 0)
{
if (!isset($this->links[$linkNum])) {
if (empty($config)) {
$config = $this->config;
} else {
$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'];
}
$this->dbName = $config['database'];
$this->typeMap = $config['type_map'];
if ($config['pk_convert_id'] && '_id' == $config['pk']) {
$this->config['pk'] = 'id';
}
if (empty($config['dsn'])) {
$config['dsn'] = 'mongodb://' . ($config['username'] ? "{$config['username']}" : '') . ($config['password'] ? ":{$config['password']}@" : '') . $config['hostname'] . ($config['hostport'] ? ":{$config['hostport']}" : '') . ($config['database'] ? "/{$config['database']}" : '');
}
$startTime = microtime(true);
$this->links[$linkNum] = new Manager($config['dsn'], $config['params']);
if (!empty($config['trigger_sql'])) {
// 记录数据库连接信息
$this->trigger('CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn']);
}
}
return $this->links[$linkNum];
}
至此,所有问题顺利解决。