28

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}

1
  • 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 stackoverflow.com/questions/63754742/… to get some background information and explanation why it works or not work. Commented Dec 18, 2022 at 10:51

15 Answers 15

50

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"
  }
);
Sign up to request clarification or add additional context in comments.

4 Comments

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
what mongoose version are you using?
thank you for that nice tip! @Carlos.V I"m using "mongoose": "^5.9.24" on node: 14.6.0
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.
27

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 
});

4 Comments

authSource admin did the trick, this is my short version await mongoose.connect("mongodb://root:example@localhost:27017/example-db?authSource=admin"); Thx
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, 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.
What issue you're facing?
21

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
});

2 Comments

can you explain what is this option "auth": { "authSource": "admin" },?
"auth": { "authSource": "admin" } means set authenticationDatabase to admin.
16

Syntax:

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

Example:

await mongoose.connect('mongodb://myUser:myPassword@localhost:27017/myDataBase?authSource=admin');

1 Comment

This worked. I simply added ?authSource=admin and it worked.
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"
   ]
}

1 Comment

For me, just add user, pass and authSource: "admin" and works like a charm. Thanks a lot.
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.

Comments

4

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']
    }
})

Comments

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

Comments

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'
);

Comments

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.

Comments

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

Comments

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);
  });

Comments

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 {}

Comments

0

It helped me to write everything I needed in the options:

await mongoose.connect("mongodb://localhost:27017", {
            user: "root",
            pass: "secret",
            dbName: "motos",
   });

1 Comment

How does this add more value on top of all the highly upvoted answers? And you are not specifying authSource for correct authentication
-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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.