MongoDB/Mongoose Connection Error when Dbname is used in the connection string

Viewed 1131

A NodeJS app uses mongoose 5.6.0 to connect to MongoDB 4.0.10 which runs on localhost inside a docker container.

The connection can be established when we use

const mongoUri = 'mongodb://admin:mypassword@127.0.0.1:27017'
mongoose.connect(mongoUri)

Problem: We start getting authentication errors when we include the name of the database we are connecting to. There is no problem using Python to connect to the same MongoDB database.

const mongoUri = 'mongodb://admin:mypassword@127.0.0.1:27017/my-db'
mongoose.connect(mongoUri)

and also tried

const mongoUri = 'mongodb://admin:mypassword@127.0.0.1:27017/my-db'
mongoose.connect(mongoUri, { useNewUrlParser: true })

UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: Authentication failed.

Why is it unable to make the connection and how can we solve this problem?

Update

Found the solution to be

const mongoUri = 'mongodb://admin:mypassword@127.0.0.1:27017'
mongoose.connect(mongoUri, { useNewUrlParser: true, dbName: 'my-db' })

Why must the dbname be passed as an option instead of including it in the connection string?

2 Answers

This has worked for me, thanks.

var result = await mongoose.connect('mongodb://root:example@localhost:27017/', {useNewUrlParser: true,dbName: 'my-db'})

Short answer: Add ?authSource=admin to URI string or use {authSource:"admin"}

const mongoUri = 'mongodb://admin:mypassword@127.0.0.1:27017/my-db?authSource=admin'
mongoose.connect(mongoUri)

Follow this answer https://stackoverflow.com/a/68137961/12280326 for detailed explanation.

Related