Mongodb connection error

  mongodb, question

Ming Mingdb.authReturns 1, butmongo -u admin -pIs failure, why?

Andy liwr @ andiiwrpc: ~/document/xiaodi ftp/nodejs/xiaodi todolist $ mongo
 MongoDB shell version: 2.6.10
 connecting to: test
 > use admin
 switched to db admin
 > db.auth("admin", "123456")
 1
 > db.auth("admin", "1234535")
 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 }
 0
 > exit
 bye
 Andy liwr @ andiiwrpc: ~/document/xiaodi ftp/nodejs/xiaodi todolist $ mongo-uadmin-p
 MongoDB shell version: 2.6.10
 Enter password:
 connecting to: test
 2016-07-31T22:41:33.520+0800 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1287
 exception: login failed

I met the same problem as the subject. I found a circle of reliable answers on the internet, and personally tried to verify and effectively solve the problem. Here are some solutions to help other newcomers to dig pits and leave something useful for the Chinese community.

The big reason for this mistake is that you directly created a.rolenon-root, and then use this user to do authentication login.

MongodbWhen doing authentication for the first time, you need to create one first.adminUser, the command is as follows:

use admin
 db.createUser(
 {
 user: "admin",
 pwd: "password",
 roles: [ { role: "root", db: "admin" } ]
 }
 );
 exit;

After completing this step, exitMongodb, end its process, restartMongodb:mongod --authOr ..mongod -f path/to/configfile, authentication login with previously created user

mongo -u admin -p password --authenticationDatabase admin

After logging in successfully, create a database with otherroleOtheruserFor example, here I create a computer that can read and writetestOf database permissionstestuser

use test
 db.createUser(
 {
 user: "testuser",
 pwd: "test",
 roles: [ { role: "readWrite", db: "test" } ]
 }
 );

After that, through the creation of otheruserIf you do authentication login again, you will not report the above mistakes again.

The pit here is,mongodbThe official document of the said “create one first”{role: "userAdminAnyDatabase", db:""}In fact, the first user to be created when the authentication mode is turned on is the ownerrootRole-basedadminAnd then throughadminTo create users of other roles.

The only reliable answer to this question isHereStudents with good English can go directly to the original text.