无法使用 Mongoose 在 MongoDB Atlas 数据库上 read/write

Cannot read/write on a MongoDB Atlas database using Mongoose

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

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 即使我的 url 正在连接到 testdb.

不确定您是否看到这个,但这可能是因为您在空闲集群上?希望这有帮助。

更新

我进一步调查了问题并自行重现。我得到了同样的错误。但是,我注意到 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

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

这对我有用

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

我遇到了同样的问题。我尝试了很多连接字符串,但 老年人 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,至少对于免费集群是这样。

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