Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose connection authentication failed

With this help, I created a super user in the mongo shell: Create Superuser in mongo

user: "try1"
passw: "hello"

In mongo cmd, I have 3 databases: 'admin', 'myDatabase' and 'local'.

Now I try to use this authorized connection to the database called 'myDatabase'.

mongoose.connect('mongodb://try1:hello@localhost:27017/myDatabase');

But this is the error I get:

name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }
Mongoose disconnected
Mongoose disconnected through ${msg}

like image 581
Tichel Avatar asked Aug 08 '17 19:08

Tichel


People also ask

Why is my MongoDB not connecting?

Ensure that your MongoDB instance is running: Compass must connect to a running MongoDB instance. Also check you have installed MongoDB and have a running mongod process. You should also check that the port where MongoDB is running matches the port you provide in the compass connect.

What does authentication fail mean?

If you receive this error message, that means that the username and/or password that you have entered is incorrect. The error message states “Authentication failed! Try again.” You may have locked your account after too many attempts and your account will need to be reset. Contact the Help Desk if this is the case.


2 Answers

I had the same problem many hours ago, and after all I solve it. My code is:

mongoose.createConnection(
  "mongodb://localhost:27017/dbName",
  {
    "auth": {
      "authSource": "admin"
    },
    "user": "admin",
    "pass": "password"
  }
);
like image 135
kartGIS Avatar answered Oct 16 '22 20:10

kartGIS


Further to @kartGIS, I've added one more option to make the connection code perfect as possible.

mongoose.connect("mongodb://localhost:27017/databaseName", {
    "auth": { "authSource": "admin" },
    "user": "username",
    "pass": "password",
    "useMongoClient": true
});
like image 19
Temp O'rary Avatar answered Oct 16 '22 22:10

Temp O'rary