Изначально я создал пользователя mongodb через mongoshell вот так:-
Код: Выделить всё
use test_mongodb;
db.createUser({user: "test_mongodbu", pwd: "test_password", roles: [{ role: "dbOwner", db: "test_mongodb"}]})
Код: Выделить всё
MONGODB_CONNECTION=mongodb
MONGODB_HOST=localhost
MONGODB_PORT=27017
MONGODB_DATABASE=test_mongodb
MONGODB_USERNAME=test_mongodbu
MONGODB_PASSWORD=test_password
MONGODB_MASTER_DATABASE=test_mongodb
Код: Выделить всё
use MongoDB\Client as MongoClient;
use MongoDB\Driver\Manager as MongoManager;
use MongoDB\Driver\Command as MongoCommand;
$databaseName = $username; // 'little_buds'
$collectionName = 'test';
$connectionString = 'mongodb://' . env('MONGODB_USERNAME') . ':' . env('MONGODB_PASSWORD') . '@' . env('MONGODB_HOST') . ':' . env('MONGODB_PORT') . '/?authSource=' . env('MONGODB_DATABASE');
$client = new MongoClient($connectionString); // Connect to MongoDB server
$manager = new MongoManager($connectionString);
$database = $client->$databaseName; // Dynamically create a database
$command = array(
'grantRolesToUser' => env('MONGODB_USERNAME'),
'roles' => array(
array(
'role' => 'dbOwner',
'db' => $databaseName
)
)
); // command to grant the role of 'dbOwner' to existing user test_mongodbu
$manager->executeCommand(env('MONGODB_DATABASE'), new MongoCommand($command)); // executing the command
$database->$collectionName->insertOne(array('key' => 'value')); // Insert a document into a collection
code>
Я получаю эту ошибку-
Код: Выделить всё
Not authorized on little_roses to execute command { insert: "test", ordered: true, $db: "little_buds", lsid: { id: UUID("d9ca3d5f-4299-4545-a487-7c565bc59ed4") } }
Подробнее здесь: https://stackoverflow.com/questions/786 ... -using-php