Uncaught error class mongo not found

What are you trying to achieve? I am using MongoDB when the module error, it occurred in the connection initialization place. I would like to use this module to initialize the test data so that the...

What are you trying to achieve?

I am using MongoDB when the module error, it occurred in the connection initialization place. I would like to use this module to initialize the test data so that the test results are always correct.

I look at the initial connection of the source code and found the following code to return false.

$this->legacy = extension_loaded('mongodb') === false &&
            class_exists('\MongoClient') &&
            strpos(MongoClient::VERSION, 'mongofill') === false;

I modified its results, hoping to enter this method, but there was no class to find the error. It is the php tool class, should not appear less than the case.

/**
     * Connect to the Mongo server using the legacy mongo extension.
     */
    protected function setupMongo($dsn, $options)
    {
        try {
            $this->client = new MongoClient($dsn, $options);
            $this->dbh    = $this->client->selectDB($this->dbName);
        } catch (MongoConnectionException $e) {
            throw new ModuleException($this, sprintf('Failed to open Mongo connection: %s', $e->getMessage()));
        }
    }
Codeception PHP Testing Framework v2.3.3
Powered by PHPUnit 5.7.21 by Sebastian Bergmann and contributors.

Fatal error: Uncaught Error: Class 'MongoClient' not found in /www/xxx/xxx/vendor/codeception/base/src/Codeception/Lib/Driver/MongoDb.php:99
Stack trace:
#0 /www/xxx/xxx/vendor/codeception/base/src/Codeception/Lib/Driver/MongoDb.php(148): CodeceptionLibDriverMongoDb->__construct('mongodb://xx.xx...','mongouser', 'xxxxxxxxxxxxxxx...')
#1 /www/xxx/xxx/vendor/codeception/base/src/Codeception/Module/MongoDb.php(98): CodeceptionLibDriverMongoDb::create('mongodb://xx.xx...', 'mongouser', 'xxxxxxxxxxxx...')
#2 /www/xxx/xxx/vendor/codeception/base/src/Codeception/SuiteManager.php(80): CodeceptionModuleMongoDb->_initialize()
#3 /www/xxx/.composer/vendor/codeception/codeception/src/Codeception/Codecept.php(182): CodeceptionSuiteManager->initialize()
#4 /www/xxx/.composer/vendor/codeception/codeception/src/Codeception/Codecept.php(153): CodeceptionCodecept->runSuite(Array, 'api', 'ApiControllerTe...')
#5 /www/xxx/.composer/vendor/codeception/cod in /www/xxx/xxx/vendor/codeception/base/src/Codeception/Lib/Driver/MongoDb.php on line 99

You can see that this is two questions.

What do you get instead?

Provide console output if related. Use -vvv mode for more details.

[xxx@VM_xx_centos editor]$ codecept -vvv run api ApiControllerTest:testActionArticle4
Codeception PHP Testing Framework v2.3.3
Powered by PHPUnit 5.7.21 by Sebastian Bergmann and contributors.
exception: login failed

  Rebuilding ApiTester...

Api Tests (1) -----------------------------------------------------------------------------------------------------------------------------------------------------
Modules: Yii2, MongoDb, HelperApi, REST, PhpBrowser
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
✔ ApiControllerTest: Action article4 (0.00s)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------


Time: 221 ms, Memory: 10.00MB

OK (1 test, 0 assertions)

Provide test source code if related

public function testActionArticle4()
{
    //empty
}

Details

  • Codeception version: v2.3.3
  • PHP Version: 7.1.9
  • Operating System: centos6
  • Installation type: Composer
  • List of installed packages (composer show)
behat/gherkin                      v4.4.5  Gherkin DSL parser for PHP 5.3
bower-asset/bootstrap              v3.3.7  The most popular front-end framework for developing responsive, mobile first projects on the web.
bower-asset/jquery                 2.2.4
bower-asset/jquery.inputmask       3.3.8   Inputmask is a javascript library which creates an input mask.  Inputmask can run against vanilla javascript, jQuer...
bower-asset/punycode               v1.3.2
bower-asset/typeahead.js           v0.11.1
bower-asset/yii2-pjax              v2.0.6
cebe/markdown                      1.1.2   A super fast, highly extensible markdown parser for PHP
codeception/base                   2.3.5   BDD-style testing framework
codeception/specify                0.4.6   BDD code blocks for PHPUnit and Codeception
codeception/verify                 0.3.3   BDD assertion library for PHPUnit
curl/curl                          1.6.1   cURL class for PHP
doctrine/instantiator              1.0.5   A small, lightweight utility to instantiate objects in PHP without invoking their constructors
ezyang/htmlpurifier                v4.9.3  Standards compliant HTML filter written in PHP
flow/jsonpath                      0.3.4   JSONPath implementation for parsing, searching and flattening arrays
fzaninotto/faker                   v1.7.1  Faker is a PHP library that generates fake data for you.
guzzlehttp/guzzle                  6.3.0   Guzzle is a PHP HTTP client library
guzzlehttp/promises                v1.3.1  Guzzle promises library
guzzlehttp/psr7                    1.4.2   PSR-7 message implementation that also provides common utility methods
myclabs/deep-copy                  1.6.1   Create deep copies (clones) of your objects
ogheo/yii2-htmlcompress            1.1.0   Compress HTML output into a single line
phar-io/manifest                   1.0.1   Component for reading phar.io manifest information from a PHP Archive (PHAR)
phar-io/version                    1.0.1   Library for handling version information and constraints
phpdocumentor/reflection-common    1.0.1   Common reflection classes used by phpdocumentor to reflect the code structure
phpdocumentor/reflection-docblock  4.1.1   With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information ...
phpdocumentor/type-resolver        0.4.0
phpspec/php-diff                   v1.1.0  A comprehensive library for generating differences between two hashable objects (strings or arrays).
phpspec/prophecy                   v1.7.2  Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage          5.2.2   Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator          1.4.2   FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-text-template          1.2.1   Simple template engine.
phpunit/php-timer                  1.0.9   Utility class for timing
phpunit/php-token-stream           2.0.1   Wrapper around PHP's tokenizer extension.
phpunit/phpunit                    6.2.4   The PHP Unit Testing framework.
phpunit/phpunit-mock-objects       4.0.4   Mock Object library for PHPUnit
psr/http-message                   1.0.1   Common interface for HTTP messages
psr/log                            1.0.2   Common interface for logging libraries
sebastian/code-unit-reverse-lookup 1.0.1   Looks up which function or method a line of code belongs to
sebastian/comparator               2.0.0   Provides the functionality to compare PHP values for equality
sebastian/diff                     1.4.3   Diff implementation
sebastian/environment              3.1.0   Provides functionality to handle HHVM/PHP environments
sebastian/exporter                 3.1.0   Provides the functionality to export PHP variables for visualization
sebastian/global-state             2.0.0   Snapshotting of global state
sebastian/object-enumerator        3.0.3   Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector         1.1.1   Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context        3.0.0   Provides functionality to recursively process PHP variables
sebastian/resource-operations      1.0.0   Provides a list of PHP built-in functions that operate on resources
sebastian/version                  2.0.1   Library that helps with managing the version number of Git-hosted PHP projects
stecman/symfony-console-completion 0.7.0   Automatic BASH completion for Symfony Console Component based applications.
swiftmailer/swiftmailer            v5.4.8  Swiftmailer, free feature-rich PHP mailer
symfony/browser-kit                v3.3.9  Symfony BrowserKit Component
symfony/console                    v3.3.9  Symfony Console Component
symfony/css-selector               v3.3.9  Symfony CssSelector Component
symfony/debug                      v3.3.9  Symfony Debug Component
symfony/dom-crawler                v3.3.9  Symfony DomCrawler Component
symfony/event-dispatcher           v3.3.9  Symfony EventDispatcher Component
symfony/finder                     v3.3.9  Symfony Finder Component
symfony/polyfill-mbstring          v1.5.0  Symfony polyfill for the Mbstring extension
symfony/yaml                       v3.3.9  Symfony Yaml Component
tencentyun/php-sdk                 2.0.2   php sdk for app.qcloud.com image service
theseer/tokenizer                  1.1.0   A small library for converting tokenized PHP source code into XML and potentially other formats
webmozart/assert                   1.2.0   Assertions to validate method input/output with nice error messages.
whitemerry/phpkin                  1.2.6   PHP Zipkin implementation
yiisoft/yii2                       2.0.12  Yii PHP Framework Version 2
yiisoft/yii2-bootstrap             2.0.6   The Twitter Bootstrap extension for the Yii framework
yiisoft/yii2-composer              2.0.5   The composer plugin for Yii extension installer
yiisoft/yii2-debug                 2.0.11  The debugger extension for the Yii framework
yiisoft/yii2-faker                 2.0.3   Fixture generator. The Faker integration for the Yii framework.
yiisoft/yii2-gii                   2.0.5   The Gii extension for the Yii framework
yiisoft/yii2-mongodb               2.1.3   MongoDB extension for the Yii framework
yiisoft/yii2-swiftmailer           2.0.7   The SwiftMailer integration for the Yii framework
  • Suite configuration:
actor: ApiTester
modules:
    enabled:
        - Yii2:
            part: [orm, fixtures]
        - MongoDb:
            dsn: 'mongodb://xxx.xxx.xxx.xxx:27017/xxx_dev_tests?authSource=admin&readPreference=secondaryPreferred'
            user: 'mongouser'
            password: 'xxxxxxxxxxxxxxxxx'
            dump: 'tests/_data/dump.js'
            populate: true # run populator before all tests
            cleanup: true # run populator before each test
        - HelperApi
        - REST:
            url: http://xxx-dev.xxx.com
            depends: PhpBrowser
            part: Json

Installed Mongo on my machine, and enabled Mongo/Mongo Cache/Mongo Field Storage (using this tutorial http://groups.drupal.org/node/183279). When I use drush, I get this error everytime:

Fatal error: Class 'Mongo' not found

When I comment out the cache settings in settings.php, drush works. How can I work around this and still use Mongo Cache?

Comments

fgm’s picture

Comment #1

fgm

Primary language French

Location Paris, France

CreditAttribution: fgm commented 2 April 2012 at 12:21

Title: Fatal error: Class ‘Mongo’ not found — using drush » Implement Mongodb extension check for the cache plugin, not just in mongodb_requirements().

It looks like you did not enable the mongodb extension in PHP, which is not automatic when you install mongodb itself.

The module should catch the missing extension, though. It already checks for its presence in hook_requirements() but cache plugins run without a hook_requirements() check. Adjusting issue title accordingly

  • Log in or register to post comments

kevinquillen’s picture

Weird, I have extension=mongo.so in my php.ini, and see it enabled in phpinfo.

  • Log in or register to post comments

kevinquillen’s picture

Let me clarify, I can create nodes and fields and see them appear in my mongo database. Its when I try to use Mongo Cache module that drush breaks.

  • Log in or register to post comments

MiSc’s picture

Comment #4

MiSc CreditAttribution: MiSc commented 2 April 2012 at 12:47

Which settings are you using for the MongoDB cache in settings.php?

  • Log in or register to post comments

kevinquillen’s picture

settings.php:

$conf['mongodb_connections'] = array(
 'default' => array(                             // Connection name/alias
   'host' => 'localhost',                       // Omit USER:PASS@ if Mongo isn't configured to use authentication.
   'db' => 'newmongo'                   // Database name. Make something up, mongodb will automatically create the database.
  ),
);

include_once('./includes/cache.inc');

# -- Configure Cache
$conf['cache_backends'][] = 'sites/all/modules/mongodb/mongodb_cache/mongodb_cache.inc';
$conf['cache_class_cache'] = 'DrupalMongoDBCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalMongoDBCache';
$conf['cache_default_class'] = 'DrupalMongoDBCache';

# Field Storage
$conf['field_storage_default'] = 'mongodb_field_storage';

# -- Don't touch SQL if in Cache
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

  • Log in or register to post comments

MiSc’s picture

Comment #6

MiSc CreditAttribution: MiSc commented 2 April 2012 at 14:48

cache_backends does not work for me either (see http://drupal.org/node/1413178), add:

include_once('./sites/all/modules/mongodb/mongodb_cache/mongodb_cache.inc');

(If you mongodb is in the sites all…)

EDIT: sorry, removed #…

  • Log in or register to post comments

MiSc’s picture

Comment #7

MiSc CreditAttribution: MiSc commented 4 April 2012 at 08:36

@Kevin Quillen see: #1514556: Example settings for cache in README.txt does not work

You should remove:

include_once('./includes/cache.inc');

And:

$conf['cache_class_cache'] = 'DrupalMongoDBCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalMongoDBCache';

To get

$conf['cache_backends'][] = 'sites/all/modules/mongodb/mongodb_cache/mongodb_cache.inc';

To work.

  • Log in or register to post comments

MiSc’s picture

Comment #8

MiSc CreditAttribution: MiSc commented 4 April 2012 at 19:04

Title: Implement Mongodb extension check for the cache plugin, not just in mongodb_requirements(). » Fatal error: Class ‘Mongo’ not found — using drush
  • Log in or register to post comments

MiSc’s picture

Comment #9

MiSc CreditAttribution: MiSc commented 5 April 2012 at 07:18

@Kevin Quillen did it work for you?

  • Log in or register to post comments

MiSc’s picture

Status: Active » Postponed (maintainer needs more info)
  • Log in or register to post comments

MiSc’s picture

Status: Postponed (maintainer needs more info) » Fixed

Marked is fixed in lack of response.

  • Log in or register to post comments
Status: Fixed » Closed (fixed)

Automatically closed — issue fixed for 2 weeks with no activity.

  • Log in or register to post comments

pwaterz’s picture

Status: Closed (fixed) » Active

I am also getting this error. I greped the code for ‘class Mongo’ and found nothing. On line 32 of mongodb.module you call $mongo = new Mongo($host);

  • Log in or register to post comments

pwaterz’s picture

Status: Active » Closed (fixed)

Ahh I just realized that is supposed to come from the php extension. AHHH…I am missing extension=mongo.so in my php cli php.ini

  • Log in or register to post comments

pwaterz’s picture

This is really off topic, but the install.txt for this module could use some work.

  • Log in or register to post comments

MiSc’s picture

@pwaterz, have you checked the README.txt in the latest dev?

  • Log in or register to post comments

Anonymous’s picture

Comment #17

Anonymous (not verified) CreditAttribution: Anonymous commented 4 August 2012 at 18:50

Version: 7.x-1.0-beta2 » 7.x-1.0-rc1
Status: Closed (fixed) » Active

Hi, I keep getting this issue when trying to run ‘drush mongodb-migrate-prepare’.

Error: Class ‘Mongo’ not found in mongodb.module line 34

Running drush on Windows 7 from the drush installer for windows. I run drush in the root of my drupal site.

MongoDB PHP is loaded, working and seen in phpinfo().

But for some reason, running drush does not load the mongodb php?

Could it be 32bit / 64bit conflict? My PHP/mongo is 64 bit, but I think drush-for-windows is 32 bit?

  • Log in or register to post comments

fgm’s picture

Comment #18

fgm

Primary language French

Location Paris, France

CreditAttribution: fgm commented 4 August 2012 at 18:54

More likely you are not using the same php.ini for drush (CLI SAPI) and web (on Windows, probably ISAPI or FASTCGI SAPI): if your php.ini for CLI does not load mongo.so that makes sense.

Can you check «php -i» from the command line to see if the Mongo is loaded ?

  • Log in or register to post comments

Anonymous’s picture

Comment #19

Anonymous (not verified) CreditAttribution: Anonymous commented 4 August 2012 at 19:07

Status: Active » Closed (fixed)

PHP CLI of course. Drush for windows has its own PHP with php.ini

  • Log in or register to post comments

fgm’s picture

Comment #20

fgm

Primary language French

Location Paris, France

CreditAttribution: fgm commented 5 August 2012 at 16:48

That’s a good start: but does that php.ini load the Mongo extension ?

On Debian, all php.ini default to loading from the conf.d directory and there’s a mongo.conf there, so the extension is always loaded whatever the SAPI. But maybe this is different on Windows ? When you run php -i, do you see the mongo extension listed ?

  • Log in or register to post comments

couloir007’s picture

I’m running Ubuntu and was getting this error trying to drush cc all. I did this:

sudo ln -s /etc/php5/mods-available/mongo.ini /etc/php5/cli/conf.d/mongo.ini

and now all is well.

  • Log in or register to post comments

Попытка создать новое соединение Mongo, используя следующее: $client = new Mongo();

К сожалению, это приводит к следующей ошибке: «Непринятая ошибка: класс» Монго «не найден в». Я также попробовал MongoClient, на всякий случай это проблема.

Чтобы сделать вещи более запутанными, запуск phpinfo() в том же файле приводит к следующему.

Изображение 443501

Любая помощь будет принята с благодарностью.

19 фев. 2016, в 21:52

Поделиться

Источник

2 ответа

Оказывается, это проблема в официальной документации водителя.

Вам нужно использовать new MongoDBClient и использовать библиотеку PHP, а не new MongoDBDriverClient как было предложено.

Oliver Dunk
20 фев. 2016, в 12:12

Поделиться

Ещё вопросы

  • 0Как получить доступ к `$ scope.search.value`?
  • 0Обучение распознавателю лица занимает много времени
  • 0Eclipse for PHP error Java была запущена, но вернула код ошибки 13
  • 0Предупреждение: недопустимое смещение строки: php [duplicate]
  • 0скрыть и показать div нажмите на
  • 0php искать исходный код URL для конкретного слова, а затем перенаправить на URL
  • 0незаконные действия в блокноте ++
  • 0Получить как значение в строке как столбец?
  • 1Как фильтровать уникальные строки двумерного массива на основе вложенных элементов и суммируемых значений одновременно в Javascript
  • 1питон — дубликат лототона на экстракторе
  • 0Не могу получить доступ к запросу пароля из MySQL в Ubuntu
  • 0JavaScript IF ELSE оператор в строке
  • 0Как преобразовать результат запроса базы данных в JSON, содержащийся в одном массиве?
  • 1Как изменить каталог DLL в проекте C #
  • 0ASP.net MVC4 Скрыть исходный код HTML, код Javascript
  • 0Как получить фрагмент HTML через Applescript с помощью Javascript
  • 1InstancePerApiControllerType не работает
  • 1Поиск победителя в Tic-Tac-Toe (Java с использованием 2-D массивов)
  • 1Android: повторяющийся рабочий процесс Android. Огонь и забыть?
  • 1Нужно повторить цикл 3 раза для особых условий
  • 1Точки останова не достигнуты, символы не загружены
  • 0Тестирование пользовательского ввода с селеном
  • 0Ошибка C ++: сбой отладочного утверждения
  • 1Чтение cookie в приложении WPF
  • 0Передача входных данных между текстовыми полями HTML
  • 0Используйте Чжу Раманан код в веб-приложении
  • 1Используйте один метод для возврата данных с разными типами
  • 0Как заставить скрытый элемент скользить вниз, не затрагивая другие элементы в той же строке
  • 0Обновлять столбец из одной таблицы в другую, только если идентификатор совпадает в 2 таблицах, а не в третьей
  • 1Ошибка при отбрасывании исключения
  • 0Проверка входа пользователя в базу данных
  • 1Программирование последовательного порта на Android-Beagleboard
  • 1Не удалось загрузить класс com.android.build.gradle.managed.BuildType_Impl
  • 0MYSQL LEFT JOIN 3 таблицы (1-я таблица возвращает пустые значения)
  • 1Как я могу проверить, равен ли ввод букв в массиве?
  • 0выровнять HTML-форму с проблемой CSS
  • 0проблема с вложенными тегами
  • 0изображение накладывается на другое изображение
  • 0Можно сделать изображение повторяться горизонтально, не будучи фоновым изображением
  • 0выбор определенных столбцов в одном или трех столбцах в MySql
  • 0Javascript Назначить новое поле для объекта
  • 1PInvoke DnsQueryEx Async
  • 0Как добавить полосу прокрутки в контейнер перетаскивания с AngularJS?
  • 0PhoneGap / JQueryMobile приложение сборки теряет стиль
  • 0Сопоставление строки (в первой таблице) с несколькими столбцами (во второй таблице) из таблицы с использованием MySQL
  • 1Значок Android Marketplace
  • 1Преобразование кода JavaScript в код Android — как добавить реферер в запросе POST?
  • 0Smart База данных настройки / макета
  • 0opencv: разные способы заполнения cv :: mat
  • 1Как отсортировать массив [] без учета регистра? [Дубликат]

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:
  • Unable to set graphics mode error
  • Unable to set display mode как исправить
  • Unable to save screenshot because of an internal error the format may not be supported
  • Unable to save current preset reshade как исправить
  • Unable to save current preset make sure you have write permission как исправить