0

I have a node.js app that uses MongoDB as a database. I have also the management of MongoDB. When the app starts, it connects to MongoDB without any problem. I am trying to let the user defines which database he/she will connect to. To do that I create mongo.conf like that:

enter image description here

And in the app, I defined the connection uri like that: MONGODB_URL="mongodb://< username>:< password>@34.72.5.46:27017/"

The database user has the root role. As I mentioned, in first opening the app connects to the database. In the first opening, I am using mongoose.connect But when the user inserts a database name that doesn't exist, via the app, I am using mongoose.createConnection. And then I get this error:

MongoNetworkError: failed to connect to server [34.72.5.46:27017] on first connect [MongoError: Authentication failed.

What should I do?

Arda Örkin
  • 121
  • 3
  • 8
  • Maybe share the code you are using to connect? Most likely the `username:password` are incorrect. – Šimon Kocúrek Aug 04 '21 at 11:04
  • Please don't paste screenshots, use formatted text. See https://meta.stackoverflow.com/a/285557/3027266 – Wernfried Domscheit Aug 04 '21 at 12:36
  • See this: https://stackoverflow.com/questions/63754742/authentication-failure-while-trying-to-save-to-mongodb/63755470#63755470 – Wernfried Domscheit Aug 04 '21 at 12:41
  • @ŠimonKocúrek username and password are correct. As I mentioned, I can connect at the first opening of the app. But then I am using createConnection method of mongoose library. The code is like that: ```await mongoose .createConnection(process.env.MONGODB_URL.concat(req.body.company))``` – Arda Örkin Aug 04 '21 at 13:44
  • What does the mongod log say about the authentication attempt? – Joe Aug 04 '21 at 22:46
  • @Joe well I can't retrieve logs back but I solved my issue. It has been needed to add "?authSource=admin" at the end of the mongo URI. – Arda Örkin Aug 05 '21 at 11:40

1 Answers1

1

I solved my issue. It has been needed to add "?authSource=admin" at the end of the mongo URI

Arda Örkin
  • 121
  • 3
  • 8