由于业务需要, 最近我也开始学习了mongo, 公司用的3.2.3版本, 遇到最大的问题就是call to a member function selectcollection() on a non-object, 其实看过错误提示就会很明白, 这个原因是由于缺少数据库名引起的.
知道了错误原因就很容易解决这个问题了.
首先, 我的数据库配置文件是这样写的:return array(
'db_type' => 'mysql',
'db_host' => 'localhost',
'db_name' => 'xxx',
'db_user' => 'xxx',
'db_pwd' => 'xxx',
'db_port' => '3306',
'db_prefix' => '',
//密钥
authcode => 'xxx',
cookie_prefix => 'xxx',
'mongo'=>array(
'db_type' => 'mongo', // 数据库类型
'db_host' => 'localhost', // 服务器地址
'db_name' => 'xxx', // 数据库名
'db_user' => 'xxx', // 用户名
'db_pwd' => 'xxx', // 密码
'db_port' => '27017', // 端口
'db_prefix' => 'xx'
)
);默认使用mysql的链接方式, 只有在某些页面才会用到mongo.
so 在使用的时候是这样: m(product,,mongo);大家可以去了解一下这个m方法的源码和具体的参数是干什么用的, 这里有个小问题, 就是中间的参数是表前缀, 但是我为空了系统竟然使用mysql的表前缀,并且我mongo的配置里面也写了表前缀是为空的,都不行, 有知道的大神说一下,小弟感激不尽.
然后就是修改library\think\db\driver\mongo.class.php这个文件:
其中switchcollection函数里面有一段代码是这样的:if(!empty($db)) { // 传人db则切换数据库
// 当前mongodb对象
$this->_dbname = $db;
$this->_mongo = $this->_linkid->selectdb($db);
}我们在其后面加个else:if(!empty($db)) { // 传人db则切换数据库
// 当前mongodb对象
$this->_dbname = $db;
$this->_mongo = $this->_linkid->selectdb($db);
}else{
$config = c('mongo');
$db = $config['db_name'];
$this->_dbname = $db;
$this->_mongo = $this->_linkid->selectdb($db);
}开头我也说了, 造成这个错误的原因就是缺少数据库名, so 我们可以加上去, 这样就解决了.
ad:真正免费,域名+虚机+企业邮箱=0元