Cannot read/write on a MongoDB Atlas database using Mongoose

风格不统一 提交于 2019-12-24 20:29:10

问题


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')
})

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'
})

I get the following error:

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

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.

Cheers!


回答1:


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

UPDATE

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.

The connection string looks like this:

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.

It looks like the free version of MongoDB Atlas launches with v3.4




回答2:


If you are using free cluster. change 'admin' to 'test' in the path: mongodb+srv://username:password@cluster0-yauj8.mongodb.net/test?retryWrites=true&w=majority

This worked for me




回答3:


Going off @rithesh-mys 's answer. Replacing it with "test" is specifying the db. So you have to change it to the db name that you would use.



来源:https://stackoverflow.com/questions/49179829/cannot-read-write-on-a-mongodb-atlas-database-using-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!