Home > Blockchain >  Authentication failure on MongoDB 6.0
Authentication failure on MongoDB 6.0

Time:12-13

Since I started to use MongoDB 6.0 I can no longer connect to the DB with Mongoose because of "Authentication failure". I kept everything the same as on MongoDB 5 but it no longer works with 6.

MongoServerError: Authentication failed.
    at Connection.onMessage (/home/leemorgan/market/market-api/node_modules/mongodb/lib/cmap/connection.js:207:30)
    at MessageStream.<anonymous> (/home/leemorgan/market/market-api/node_modules/mongodb/lib/cmap/connection.js:60:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (/home/leemorgan/market/market-api/node_modules/mongodb/lib/cmap/message_stream.js:132:20)
    at MessageStream._write (/home/leemorgan/market/market-api/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 Socket.ondata (node:internal/streams/readable:766:22)
    at Socket.emit (node:events:513:28) {
  ok: 0,
  code: 18,
  codeName: 'AuthenticationFailed',
  [Symbol(errorLabels)]: Set(1) { 'HandshakeError' }
}

Code for connecting with Mongoose:

mongoose.connect("mongodb://127.0.0.1:27017/myDB", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    auth: {authSource: "admin"},
    user: "user",
    pass: process.env.MONGODB_PASS,
    family: 4
});

I checked and re-checked the username/password a million times. I can log in to mongosh with the user, just not through Mongoose. This even happens when authentication is disabled. How do I get past this error?

CodePudding user response:

I don't see auth: {authSource in the documentation? Looks like it should be authSource: "admin",. Try:

mongoose.connect("mongodb://127.0.0.1:27017/myDB", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    user: "user",
    pass: process.env.MONGODB_PASS,
    family: 4
});

CodePudding user response:

make sure your process.env.MONGODB_PASS is not undefined other wise declare MONGODB_PASS in .env file and assign your password

console.log(process.env.MONGODB_PASS) //should return your passowrd

//your mongoDB local url with username and password
const mongoURI = `mongodb://user:{$process.env.MONGODB_PASS}@127.0.0.1:27017/myDB` 

mongoose.connect(mongoURI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  family: 4
});
  • Related