0

I am using Mongoose ORM in order to connect with database. The problem is when I am trying to place database name at the end of connection string, it's throwing me this error:

Error MongoServerError: Authentication failed.
at Connection.onMessage (/home/digvijay/mordor/subscription-backend/node_modules/mongodb/lib/cmap/connection.js:207:30)
at MessageStream.<anonymous> (/home/digvijay/mordor/subscription-backend/node_modules/mongodb/lib/cmap/connection.js:60:60)
at MessageStream.emit (node:events:513:28)
at processIncomingData (/home/digvijay/mordor/subscription-backend/node_modules/mongodb/lib/cmap/message_stream.js:132:20)
at MessageStream._write (/home/digvijay/mordor/subscription-backend/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
at writeOrBuffer (node:internal/streams/writable:391:12)
at _write (node:internal/streams/writable:332:10)
at MessageStream.Writable.write (node:internal/streams/writable:336:10)
at Socket.ondata (node:internal/streams/readable:754:22)
at Socket.emit (node:events:513:28) {
ok: 0,
code: 18,
codeName: 'AuthenticationFailed',
connectionGeneration: 0,
[Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}

Below is my code:

.env

DB_URI=mongodb://example:examplePassword@x.x.x.x:27017/lorien

connection.js

const mongoose = require('mongoose');
require('dotenv').config();

let dbCon;

mongoose.connect(process.env.DB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  "auth": { "authSource": "admin" },
  "user": "example",
  "pass": "examplePassword"
}).then(() => {
  console.log('Test db connected successfully');
})
.catch((err) => {
    console.log("Error", err);
});

When I am using connection string like this

DB_URI=mongodb://example:examplePassword@x.x.x.x:27017/

It is connecting successfully. Why is it throwing an error in first scenario when I am adding database name at the end of connection string?

halfer
  • 19,824
  • 17
  • 99
  • 186
Digvijay
  • 2,887
  • 3
  • 36
  • 86

0 Answers0