无法使用 Mongoose 读取/写入 MongoDB Atlas 数据库

Col*_*ill 1 mongoose mongodb node.js mongodb-atlas

我在 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')
})
Run Code Online (Sandbox Code Playgroud)

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

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

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

UserModel.create({
  name: 'Hello Atlas'
})
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

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

tho*_*061 6

不确定你是否看过这篇文章,但可能是因为你在一个免费集群上?希望这可以帮助。

更新

我进一步研究了这个问题并自己复制了它。我得到了同样的错误。但是,我注意到曾经有一次 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`;
Run Code Online (Sandbox Code Playgroud)

它适用于该连接字符串。

看起来MongoDB Atlas免费版本发布了 v3.4