简体   繁体   中英

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

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?

这对我有用,谢谢。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM