无法验证mongoDB

时间:2015-10-10 09:40:22

标签: php mongodb codeigniter

从mongo客户端看起来我可以进行身份​​验证:

> use admin
switched to db admin
> db.auth('admin','SECRETPASSWORD');
1
>

但是当我尝试使用此代码连接codeigniter中的配置文件时

$config['mongo_server'] = null;
$config['mongo_dbname'] = 'admin';
$config['mongo_db']['active'] = 'default';

$config['mongo_db']['default']['no_auth'] = FALSE;
$config['mongo_db']['default']['hostname'] = 'localhost';
$config['mongo_db']['default']['port'] = '27017';
$config['mongo_db']['default']['username'] = 'admin';
$config['mongo_db']['default']['password'] = 'SECRETPASSWORD';
$config['mongo_db']['default']['database'] = 'mydb';
$config['mongo_db']['default']['db_debug'] = TRUE;
$config['mongo_db']['default']['return_as'] = 'array';
$config['mongo_db']['default']['write_concerns'] = (int)1;
$config['mongo_db']['default']['journal'] = TRUE;
$config['mongo_db']['default']['read_preference'] = NULL;
$config['mongo_db']['default']['read_preference_tags'] = NULL;

$config['mongo_db']['default']['no_auth'] = FALSE;
$config['mongo_db']['test']['hostname'] = 'localhost';
$config['mongo_db']['test']['port'] = '27017';
$config['mongo_db']['test']['username'] = '';
$config['mongo_db']['test']['password'] = '';
$config['mongo_db']['test']['database'] = '';
$config['mongo_db']['test']['db_debug'] = TRUE;
$config['mongo_db']['test']['return_as'] = 'array';
$config['mongo_db']['test']['write_concerns'] = (int)1;
$config['mongo_db']['test']['journal'] = TRUE;
$config['mongo_db']['test']['read_preference'] = NULL;
$config['mongo_db']['test']['read_preference_tags'] = NULL;

我收到此错误

Unable to connect to MongoDB: Failed to connect to: localhost:27017: Authentication failed on database 'mydb' with username 'admin': auth failed

2 个答案:

答案 0 :(得分:0)

我使用一个简单的库

在config.php中创建mongo.php

$config['mongo_server'] = 'localhost';
$config['mongo_dbname'] = 'yourdbname';

和库中的Mongo.php

<?php
class CI_Mongo extends Mongo
{
    var $db;

    function CI_Mongo()
    {   
        // Fetch CodeIgniter instance
        $ci = get_instance();
        // Load Mongo configuration file
        $ci->load->config('mongo');

        // Fetch Mongo server and database configuration
        $server = $ci->config->item('mongo_server');
        $dbname = $ci->config->item('mongo_dbname');

        // Initialise Mongo
        if ($server)
        {
            parent::__construct($server);
        }
        else
        {
            parent::__construct();
        }
        $this->db = $this->$dbname;
    }
}

现在您可以在您的控制器中查看:

function index(){
 $posts = $this->mongo->yourdbname->yourcollection->find();
 foreach($posts as $id => $b){
echo $b['somefieldontable'];
}
}

答案 1 :(得分:0)

这改变了这个变量的值:

$ config ['mongo_db'] ['default'] ['no_auth'] = FALSE;

为:

$ config ['mongo_db'] ['default'] ['no_auth'] = TRUE;