skip to Main Content

I host a Mongo database on an ubuntu server. I created an admin user in order to be able to connect with Nodejs to create a database, add tables, etc. I can connect with mongoDB compass without problems but from nodeJS mongo returns an error.

connect function:

const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
//connect to db
mongoose
    .connect("mongodb://" + process.env.DB_USER_PASS + "@2.56.247.250:27017/?authMechanism=DEFAULT")
    .then(() => console.log('Connecté a la base de donné'))
    .catch((err) => console.log("Erreur de connexion :", err));

Here is the error:

Erreur de connexion : MongoServerError: Authentication failed.
    at Connection.onMessage (C:UsersarnauDesktopmessIOnode_modulesmongodblibcmapconnection.js:230:30)
    at MessageStream.<anonymous> (C:UsersarnauDesktopmessIOnode_modulesmongodblibcmapconnection.js:61:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (C:UsersarnauDesktopmessIOnode_modulesmongodblibcmapmessage_stream.js:125:16)
    at MessageStream._write (C:UsersarnauDesktopmessIOnode_modulesmongodblibcmapmessage_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',
  connectionGeneration: 0,
  [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }

2

Answers


  1. The error AuthenticationFailed means that there is a problem with your connection string and your driver cannot connect into it.
    Check for all details here: https://www.mongodb.com/docs/manual/reference/connection-string/

    Potential problems:

    1. Special Chars: From the docs: If the username or password includes the following characters: / ? # [ ] @ those characters must be converted using percent encoding.
    2. username:password format check that your environmental variable is on the right format, with : between username and pass, and no spaces.
    3. Check your auth database: When you created the user, you created on default ("admin" db is the default.) or created on a specific db, using the command use dbname. If you created on a specific db, you might need to add the auth db name on the connection string.

    You can try all the above solutions, making a connection using the mongosh command, to verify that your connection string is fine.

    Login or Signup to reply.
  2. Another possible cause of the problem your set IP address. You can fix this by adding you current IP address in the network access tab.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search