24

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}

tuomastik
  • 4,559
  • 5
  • 36
  • 48
Tichel
  • 481
  • 2
  • 10
  • 24
  • 1
    So many answers - and most of them are just the same. Most of them are correct but none of them gives any explanation. See https://stackoverflow.com/questions/63754742/authentication-failure-while-trying-to-save-to-mongodb/63755470#63755470 to get some background information and explanation why it works or not work. – Wernfried Domscheit Dec 18 '22 at 10:51

14 Answers14

47

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"
  }
);
Lionel T
  • 1,559
  • 1
  • 13
  • 30
kartGIS
  • 667
  • 1
  • 6
  • 10
  • 2
    Why is mongoose documentation so difficult!? I had tried many variations of these but just did not try this one. Finally you saved my day. Thanks @kartGIS – Temp O'rary Oct 13 '17 at 10:02
  • what mongoose version are you using? – Carlos.V Aug 02 '19 at 16:55
  • thank you for that nice tip! @Carlos.V I"m using `"mongoose": "^5.9.24"` on `node: 14.6.0` – HasBert Jul 30 '20 at 22:23
  • For me at least, mongoose version 6.2.4, I would believe all versions >= 6 require the "authSource" without the "auth" parameter. so the "authSource" should be in the main JSON object. – Johols Mar 08 '22 at 12:30
22

This is the correct answer now. others are not completely correct.

await mongoose.connect("mongodb://localhost:27017/db", {
    poolSize: 10,
    authSource: "admin",
    user: "admin",
    pass: "password",
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false 
});
M. Hamza Rajput
  • 7,810
  • 2
  • 41
  • 36
Asim Imam
  • 313
  • 1
  • 3
  • 12
  • 8
    `authSource admin` did the trick, this is my short version `await mongoose.connect("mongodb://root:example@localhost:27017/example-db?authSource=admin");` Thx – David Rearte Jul 23 '22 at 00:27
  • What happens if you move the user and pass to options, but authsource=admin is in the connection string, and if authSource admin is in options? I am facing the same issue. @asim-imam – Omkar Sep 05 '22 at 08:36
  • @Omkar, the first case you mentioned didn't work for me. I did that last year maybe I've also tried the second case you said. In my case, I was having trouble connecting admin to the database inside my ubuntu server. – Asim Imam Sep 05 '22 at 10:19
  • What issue you're facing? – Asim Imam Sep 05 '22 at 10:21
20

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
});
Temp O'rary
  • 5,366
  • 13
  • 49
  • 109
15

Syntax:

await mongoose.connect('mongodb://username:password@host:port/database?authSource=admin');

Example:

await mongoose.connect('mongodb://myUser:myPassword@localhost:27017/myDataBase?authSource=admin');
M. Hamza Rajput
  • 7,810
  • 2
  • 41
  • 36
Soraimar Bernal
  • 151
  • 1
  • 3
11

Working fine for me on Mongodb 4.2 and Mongoose 5.7.13

Node.js

const Connect = async () => {

    let url = "mongodb://localhost:27017/test_db";

    try {

        let client = await Mongoose.connect( url, {
            poolSize: 10,
            authSource: "admin",
            user: "root",
            pass: "root123", 
            useCreateIndex: true,
            useNewUrlParser: true,
            useUnifiedTopology: true
        } );

        log( "Database is connected!" );
    } catch ( error ) {
        log( error.stack );
        process.exit( 1 );
    }

}
Connect();

/etc/mongod.conf

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27017
  bindIp: 0.0.0.0 

setParameter:
   enableLocalhostAuthBypass: false

security:
  authorization: enabled

Database User

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

show users;
{
   "_id": "admin.root",
   "userId": UUID( "5db3aafd-b1fd-4bea-925e-8a4bfb709f22" ),
   "user": "root",
   "db": "admin",
   "roles": [ {
        "role": "userAdminAnyDatabase",
        "db": "admin"
      },
      {
        "role": "readWriteAnyDatabase",
        "db": "admin"
      }
   ],
   "mechanisms": [
       "SCRAM-SHA-1",
       "SCRAM-SHA-256"
   ]
}
M. Hamza Rajput
  • 7,810
  • 2
  • 41
  • 36
6

I have the same problem, and it solved by removing the 'authSource' param

/* Not working */
mongoose.connect("mongodb://localhost:27017/test", {
    "auth": { "authSource": "admin" },
    "user": "admin",
    "pass": "admin123",
    "useMongoClient": true
});

/* Working */
mongoose.connect("mongodb://localhost:27017/test", {
    "user": "admin",
    "pass": "admin123",
    "useMongoClient": true
});

Tested on Mongoose-v5.0.0.

daniel.widyanto
  • 1,609
  • 2
  • 13
  • 9
2

I got MongoParseError: credentials must be an object with 'username' and 'password' properties when used above answers.
Add username password to auth object solved the issue

  try {
    await connect("mongodb://localhost:27017/dbname", {
      auth: { username: "root", password: "example" },
      authSource: "admin",
    });
    console.log("Connected to mongo db");
  } catch (error) {
    console.error("Error connecting to mongodb", error);
  }

mongodb version 5.0.2
mongoose 6.0.4

CharukaHS
  • 561
  • 1
  • 5
  • 16
2

Respectively, if your authSource is the database ('myDB' in the example) itself and you are trying to use the ConnectionOption dbName, you have to match authSource.

await mongoose.connect('mongodb://localhost:27017,' {
  dbName: 'myDB',
  user: 'myUser',
  pass: 'asldjaskdj'
);

Will fail with error:

{
    "msg": "Authentication failed",
    "attr": {
        "mechanism": "SCRAM-SHA-1",
        "principalName": "myUser",
        "authenticationDatabase": "admin",
        "client": "...",
        "result": "UserNotFound: Could not find user \"myUser\" for db \"admin\""
    }
}

Adding authSource: 'myDB' to the connect options will work. Example:

await mongoose.connect('mongodb://localhost:27017,' {
  dbName: 'myDB',
  authSource: 'myDB',
  user: 'myUser',
  pass: 'asldjaskdj'
);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
r.beer
  • 53
  • 6
2

THIS ANSWER FOR MONGOOSE 6.7.0! USED IN NUXT 3

.env PART

MONGO_URI = "mongodb://localhost:27017/MyBeautifulDB"
MONGO_USERNAME = "mongoadmin"
MONGO_PASSWORD = "mystrongpassword"

DB CONNECTION PART

import mongoose from 'mongoose';

export default async (_nitroApp) => {
const config = useRuntimeConfig();

mongoose.connect(config.MONGO_URI, {
        maxPoolSize: 10,
        authSource: "admin",
        user: config.MONGO_USERNAME,
        pass: config.MONGO_PASSWORD
    })
    .then(() => console.log('Connected to DB'))
    .catch((e) => console.log(e));
}

nuxt.config.ts - Register your db connection file to configuration.

export default defineNuxtConfig({
    runtimeConfig: {
        MONGO_URI: process.env.MONGO_URI,
    },

    nitro: {
        plugins: ['@/server/db/index.ts']
    }
})
1

I had the same problem. I am using an older MongoDB instance. I simply added authSource=admin to the connection string and it solved the problem.

Jonas Tomanga
  • 1,069
  • 10
  • 19
1

According to the latest documentation, it should be like this:

mongoose.connect("mongodb://localhost:27017/databaseName", {
    "user": "username",
    "pass": "password",
    "authSource": "databaseName" // users are scoped to DBs
});

Tested on mongoose6.x.x

TechnoTim
  • 3,065
  • 1
  • 23
  • 28
1

works for me. i use local database, and mongoose ver 6.9.1

.env file:

DB_HOST=127.0.0.1:27017
DB_NAME=blabla
DB_USER=blablabla
DB_PWD=blablablabla

js file:

const DB = `mongodb://${process.env.DB_HOST}/${process.env.DB_NAME}`;

mongoose
  .connect(DB, {
    authSource: 'admin',
    user: process.env.DB_USER,
    pass: process.env.DB_PWD,
  })
  .then(() => {
    console.log('Connected to database.');
  })
  .catch((err) => {
    console.log(err.message);
  });
0

NOTE This answer is not answering original question but trying to help people in similar situation using NestJS

NestJS

@Module({
  imports: [
    MongooseModule.forRoot(
      'mongodb://mongo:27017/test',
      {
        auth: {
          username: 'root',
          password: 'test',
        },
        authSource: 'admin',
      },
    ),
  ],
})
export class AppModule {}
x-magix
  • 2,623
  • 15
  • 19
-2

I also faced the same issue but resolved it with this mongoose.connect(mongodb://${dbUser}:${dbPwd}@${dbHost}:${dbPort}/userInfo?authSource=admin). Assuming you have the authentication setup in mongodb.

Jah
  • 1