简体   繁体   English

在连接字符串中使用 Dbname 时出现 MongoDB/Mongoose 连接错误

[英]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. NodeJS 应用程序使用 mongoose 5.6.0 连接到 MongoDB 4.0.10,MongoDB 4.0.10 在 docker 容器内的本地主机上运行。

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.使用Python连接同一个MongoDB数据库没有问题。

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. UnhandledPromiseRejectionWarning:MongoNetworkError:第一次连接时无法连接到服务器 [127.0.0.1:27017] [MongoError:身份验证失败。

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?为什么必须将dbname作为选项传递而不是将其包含在连接字符串中?

这对我有用,谢谢。

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"}简短回答:将?authSource=admin添加到 URI 字符串或使用{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.请按照此答案https://stackoverflow.com/a/68137961/12280326获取详细说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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