MongoDB Exception – yii\mongodb\Exception
Authentication failed.
今天想在本地环境搭建下mongodb扩展,学习使用下mongodb,先是本地搭建mongodb服务,然后PHP安装扩展,这个过程很简单,可以按照 http://www.runoob.com/mongodb/mongodb-window-install.html ;
http://www.runoob.com/mongodb/mongodb-install-php-driver.html 进行安装。PHP扩展下载地址:http://pecl.php.net/package/mongo ; 完成后再shell中测试也很成功,并且安装了mongodb可视化管理工具Robo 下载地址:https://www.robomongo.org/。当我在yii中测试数据读取也写入操作时,却一直报错:
MongoDB Exception – yii\mongodb\Exception Authentication failed.
因为mongodb默认是没有用户的,所以我的数据库连接:
'mongodb' => [ 'class' => '\yii\mongodb\Connection', 'dsn' => 'mongodb://@localhost:27017/blog', ],
但是根据错误提示认证失败,而且我也没有 开启auth,搜索不到解决办法,只能自己试探添加用户,下面为添加用户的命令:(mongodb shell中执行)
> use admin switched to db admin > db.createUser( ... { ... user: "root", ... pwd: "root", ... roles: [ { role: "userAdminAnyDatabase", db: "blog" } ]... } ... )
修改数据库连接
'mongodb' => [ 'class' => '\yii\mongodb\Connection', 'dsn' => 'mongodb://root:root@localhost:27017/blog', ],
再次执行插入操作:
$collection = Yii::$app->mongodb->getCollection ('col'); $res = $collection->insert ( [ 'name' => 'John Smith22', 'status' => 2 ] ); var_dump($res);die;
程序输出:
疑惑:1、Mongodb3.4默认开启授权认证?但是从shell中不需要用户认证可以连接使用。
2、Windows下 MongoDB的配置文件mongo.conf没有。(后查看文章:http://www.cnblogs.com/liuzhiying/p/5915741.html,conf文件为自己新建配置)
Comments (0)