无法使用Mongoose在MongoDB Atlas数据库上进行读取/写入

无法使用Mongoose在MongoDB Atlas数据库上进行读取/写入

问题描述:

我在MongoDB Atlas上有一个新的沙箱群集,我正在与Node.js服务器上的猫鼬连接.这是我用来连接的代码:

I have a new sandbox cluster on MongoDB Atlas that I am connecting to with mongoose on a Node.js server. This is the code I'm using to connect:

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用户.身份验证可以正常工作.我能够连接到数据库,并且在连接上未引发任何错误.我可以通过删除密码中的字符来确认这一点-身份验证失败,并且我无法连接.

In the Atlas dashboard I have a readWriteAnyDatabase user that I am authenticating with. Authentication works as expected. I am able to connect to the database and no error is thrown on the connection. I can confirm this by removing a character in the password - authentication fails and I'm unable to connect.

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

The problem is when I try to insert documents.

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
}

据我所知,与之进行身份验证的用户应该有权在要连接的数据库上进行读写操作.我不明白的另一部分是,该错误表明即使我的URL连接到testdb,该错误仍在尝试写入admin.

As far as I know the user I'm authenticating with should have permission to read and write on the database I'm connecting to. The other part I don't understand is that the error shows that it's trying to write to admin even though my url is connecting to testdb.

干杯!

不确定您是否看到过

Not sure if you have seen this post, but it could be because you are on a free cluster? Hope this helps.

更新

我进一步研究了这个问题,并亲自复制了它.我遇到了同样的错误.但是,我注意到Atlas在某一时刻为我提供了选择连接字符串的方法.我回到该页面并选择 I am using driver 3.4 or earlier .

I looked into the problem further and reproduced it on my own. I got the same error. However, I noticed that at one point Atlas provided me with a choice of connection strings. I went back to that page and chose 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`;

它与该连接字符串一起工作.

It worked with that connection string.

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