mongodb连接失败原因排查

安装了mongodb,添加了管理员root和test数据库的用户rex,并且开启的用户认证。

按照说明文档连接mongodb数据库:$mongo = new Mongo(“mongodb://rex:123456@localhost”);

结果开启firebug之后发现报错:”NetworkError: 500 Internal Server Error - http://192.168.202.132/montest.php"

在这里尝试了很多方法都无法解决,也不清楚为什么出了错,只能再看一遍php的官方文档(http://php.net/manual/zh/mongoclient.construct.php

偶然看到这么一句:如果给出的主机都无法连接,将会抛出 MongoConnectionException 异常。

于是我开始尝试打印这个异常:

1
2
3
4
5
6
try {     
$mongo = new Mongo("mongodb://rex:123456@localhost");
} catch (Exception $e) {
print $e->getMessage();
exit();
}

输出结果是:Failed to connect to: localhost:27017: Authentication failed on database ‘admin’ with username ‘rex’: auth failed

一看便知:rex是test数据库的用户,可是代码确实默认连接数据库admin,问题就出在这里!

于是改成:$mongo = new Mongo(“mongodb://rex:123456@localhost/test”);

问题解决!