MongoDB PHP auth

authentication, mongodb, php

Solution

You need to connect to a specific database first. Just accessing $m->testlogs doesn't do that. Instead, you need to use as first line:

$m = new Mongo('mongodb://localhost/testlogs');

And optionally you could do:

$m = new Mongo('mongodb://username:password@localhost/testlogs');

Which allows you to drop the ->authenticate() call. The docs at http://php.net/manual/en/mongodb.authenticate.php also say:

In general, you should use the authenticate built into Mongo::__construct() in preference to this method. If you authenticate on connection and the connection drops and reconnects during your session, you'll be reauthenticated. If you manually authenticated using this method and the connection drops, you'll have to call this method again once you're reconnected.

Problem

I'm new to MongoDB. I started using it 2 months ago. I decided to test it for logs of one website (user behavior). At first without username and password. And it worked like a charm. I use RockMongo for admin. Then I created username and password and restarted the server. After the restart my script was unable to put data on database. However when I updated the settings of RockMongo it wirked and I can insert/update via RockMongo. I'm using MongoDB on Ubuntu 10 with PHP5. My code looks like this: ``` $m = new Mongo(); $db = $m->testlogs; $db->authenticate('username', 'password'); ``` I cannot use shell too. When trying to authenticate I'm getting the following error: "$err" : "unauthorized db:testlogs lock type:-1 client:127.0.0.1", "code" : 10057 Any help is appreciated.

Original source