Answer the question
In order to leave comments, you need to log in
MongoDB not working in yii2 advanced?
Connected MongoDB database to yii2. Gives an error:
MongoDB Exception - yii\mongodb\Exception
Authentication failed.
Caused by: MongoDB\Driver\Exception\AuthenticationException
Authentication failed.
Connected MongoDB in the common/config config in the main-local.php file (no password or user, database name is mymongo, sale collection):
'components' => [
'mongodb' => [
'class' => '\yii\mongodb \Connection',
'dsn' => 'mongodb://root:[email protected]:27017/mymongo',
],
]
model
<?php
namespace frontend\models;
use yii\base\Model;
use yii\mongodb\ActiveRecord;
class Sale extends ActiveRecord
{
/**
* @return string the name of the index associated with this ActiveRecord class.
*/
public static function collectionName()
{
return 'sale';
}
/**
* @return array list of attribute names.
*/
public function attributes()
{
return ['ids', 'name', 'path', 'file'];
}
}
?>
<?php
namespace frontend\controllers;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use frontend\models\ColorForm;
use yii\data\Pagination;
use frontend\models\Sale;
use yii\mongodb\ActiveRecord;
/**
* Site controller
*/
class SiteController extends Controller
{
public function actionSale()
{
$query = Sale::find();
$pagination = new Pagination([
'defaultPageSize' => 5,
'totalCount' => $query->count(),
]);
$sales = $query->offset($pagination->offset)->limit($pagination->limit)->all();
return $this->render('sales', [
'sales' => $sales,
'pagination' => $pagination,
]);
}
}
?>
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Countries</h1>
<ul>
<?php foreach ($sales as $sale): ?>
<li>
<?= Html::encode("{$sale->ids} ({$sale->name})") ?>:
<?= $sale->path ?>
</li>
<?php endforeach; ?>
</ul>
<?= LinkPager::widget(['pagination' => $pagination]) ?>
?>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question