【问题标题】:Cannot read/write on a MongoDB Atlas database using Mongoose无法使用 Mongoose 在 MongoDB Atlas 数据库上读/写
【发布时间】:2018-08-17 04:52:16
【问题描述】:

我在 MongoDB Atlas 上有一个新的沙盒集群,我正在使用 Node.js 服务器上的 mongoose 连接它。这是我用来连接的代码:

const mongoDbUrl =
  `mongodb+srv://${username}:${password}@mydb-sandbox-12345.mongodb.net/testdb`

mongoose.connect(mongoDbUrl)
const connection = mongoose.connection

connection.on('connected', () => {
  console.log('Connected to mongodb')
})

在 Atlas 仪表板中,我有一个 readWriteAnyDatabase 用户进行身份验证。身份验证按预期工作。我能够连接到数据库并且连接上没有引发错误。我可以通过删除密码中的一个字符来确认这一点 - 身份验证失败并且我无法连接。

问题是当我尝试插入文档时。

const UserModel = require('./models/User')

UserModel.create({
  name: 'Hello Atlas'
})

我收到以下错误:

MongoError: not authorized on admin to execute command {
insert: "users",
  documents: [
    [{
      name Hello Atlas
    } {
      _id ObjectIdHex("5aa17933d72d25730a340611")
    } {
      __v 0
    }]
  ],
  ordered: false
}

据我所知,与我进行身份验证的用户应该有权对我正在连接的数据库进行读写。我不明白的另一部分是错误表明它正在尝试写入admin,即使我的网址正在连接到testdb

【问题讨论】:

  • 另外一件值得注意的事情 - 我尝试使用 vanilla MongoDB 驱动程序编写相同的内容并且它可以工作。我使用相同的身份验证凭据连接到相同的 URL,并且能够将新的用户对象添加到 testdb。我想知道这是否与我的猫鼬配置有关。

标签: node.js mongodb mongoose mongodb-atlas


【解决方案1】:

不确定您是否看到过此post,但这可能是因为您在免费集群上?希望这会有所帮助。

更新

我进一步研究了这个问题并自己复制了它。我得到了同样的错误。但是,我注意到有一次 Atlas 为我提供了连接字符串的选择。我回到那个页面并选择了I am using driver 3.4 or earlier

连接字符串如下所示:

const mongoDbUrl = `mongodb://${username}:${password}@cluster0-shard-00-00-1wntz.mongodb.net:27017,cluster0-shard-00-01-1wntz.mongodb.net:27017,cluster0-shard-00-02-1wntz.mongodb.net:27017/testdb?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin`;

它与那个连接字符串一起工作。

看起来 MongoDB Atlas 的免费版本与 v3.4 一起发布

【讨论】:

  • hmm... 我在这里看不到任何适用于我的简单写入操作的不受支持的命令或限制,但这是可能的。不确定这是否能解释为什么它通过香草驱动程序而不是通过 Mongoose 工作,除非 Mongoose 在引擎盖下做了一些奇怪的事情。
  • 很好地了解驱动程序版本。我想我曾经尝试过 3.4 连接字符串,但我之前一定是用错了。 Vanilla 驱动程序使用 3.6 连接字符串,但 mongoose 不喜欢它。似乎工作 - 谢谢!
  • 很好的答案,你为我节省了很多时间。
【解决方案2】:

如果您使用的是免费集群。在路径中将“admin”更改为“test”: mongodb+srv://username:password@cluster0-yauj8.mongodb.net/test?retryWrites=true&w=majority

这对我有用

【讨论】:

    【解决方案3】:

    离开@rithesh-mys 的回答。用“test”替换它是指定数据库。因此,您必须将其更改为您将使用的数据库名称。

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题。我尝试了很多连接字符串,但适合老年人的 mongo shell(3.4 或更早版本)对我有用。

      mongodb://my_username:my_password@cluster0-shard-00-00.osobw.mongodb.net:27017,cluster0-shard-00-01.osobw.mongodb.net:27017,cluster0-shard-00-02.osobw.mongodb.net:27017/my_database?ssl=true&replicaSet=atlas-xw3rfy-shard-0&authSource=admin
      

      我认为较新版本的连接字符串不适用于 mongoose,至少不适用于免费集群。

      【讨论】:

        【解决方案5】:

        确保您创建的用户具有写入和读取权限。

        【讨论】:

          猜你喜欢
          • 2020-02-22
          • 2020-07-25
          • 2019-12-30
          • 1970-01-01
          • 2020-10-12
          • 2020-12-28
          • 1970-01-01
          • 2021-04-11
          • 2019-09-04
          相关资源
          最近更新 更多