MongoServerError: bad auth : Authentication failed error

632 Views Asked by At

I am following the https://www.mongodb.com/languages/mern-stack-tutorial guide. Then installed atlas using https://www.mongodb.com/docs/atlas/cli/stable/install-atlas-cli/ using windows binary installation.

I've set up everything according to the tutorials.

Versions:

  1. Node v18.6.0
  2. Npm v9.6.5
  3. Atlascli v1.6.0

I can't really change anything with the IP due to living in a dorm if that may be an issue.

config.env code (MYLOGIN AND MYPASS are taken from mongoDB database access):

ATLAS_URI=mongodb+srv://MYLOGIN:[email protected]/employees?retryWrites=true&w=majority
PORT=5000

conn.js code:

const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

var _db;

module.exports = {
  connectToServer: function (callback) {
    client.connect(function (err, db) {
      // Verify we got a good "db" object
      if (db) {
        _db = db.db("employees");
        console.log("Successfully connected to MongoDB.");
      }
      return callback(err);
    });
  },

  getDb: function () {
    return _db;
  },
};

Error message:

PS D:\**\mern\server> npm start

> [email protected] start
> node server.js

Server is running on port: 5000
D:\**\mern\server\node_modules\mongodb\lib\cmap\connection.js:202
                callback(new error_1.MongoServerError(document));
                         ^

MongoServerError: bad auth : Authentication failed.
    at Connection.onMessage (D:\**\mern\server\node_modules\mongodb\lib\cmap\connection.js:202:26)
    at MessageStream.<anonymous> (D:\**\mern\server\node_modules\mongodb\lib\cmap\connection.js:61:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (D:\**\mern\server\node_modules\mongodb\lib\cmap\message_stream.js:124:16)
    at MessageStream._write (D:\**\mern\server\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:392:12)
    at _write (node:internal/streams/writable:333:10)
    at Writable.write (node:internal/streams/writable:337:10)
    at TLSSocket.ondata (node:internal/streams/readable:766:22)
    at TLSSocket.emit (node:events:513:28) {
  ok: 0,
  code: 8000,
  codeName: 'AtlasError',
  connectionGeneration: 0,
  [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}

Node.js v18.6.0

What I've tried already:

  1. Adding a new database user with admin privileges (Authentication method is SCRAM).
  2. Setting network access to 0.0.0.0.
  3. Tried pulling the github repo https://github.com/mongodb-developer/mern-stack-example it results with the same issue.
  4. I have tried connecting to the database using the "MongoDB for VS Code" extension on VSCODE and it worked fine though when I do npm start it fails.
0

There are 0 best solutions below