【问题标题】:MongoDB/Mongoose Connection Error when Dbname is used in the connection string在连接字符串中使用 Dbname 时出现 MongoDB/Mongoose 连接错误
【发布时间】:2019-11-03 09:35:54
【问题描述】:

NodeJS 应用使用 mongoose 5.6.0 连接到 MongoDB 4.0.10,MongoDB 4.0.10 在 docker 容器内的 localhost 上运行。

我们使用的时候就可以建立连接了

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

问题:当我们包含我们要连接的数据库的名称时,我们开始收到身份验证错误。使用Python连接同一个MongoDB数据库没有问题。

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

也试过了

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.

为什么无法建立连接,我们该如何解决这个问题?

更新

找到解决办法

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

为什么必须将dbname 作为选项传递,而不是将其包含在连接字符串中?

【问题讨论】:

    标签: javascript node.js mongodb docker mongoose


    【解决方案1】:

    简答:将 ?authSource=admin 添加到 URI 字符串或使用 {authSource:"admin"}

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

    请关注此回答https://stackoverflow.com/a/68137961/12280326了解详细说明。

    【讨论】:

      【解决方案2】:

      这对我有用,谢谢。

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

      【讨论】:

      • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 2020-07-23
      • 2020-10-26
      • 2019-06-07
      • 2020-10-11
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      相关资源
      最近更新 更多