我在 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 连接到 …