Couldn't be able to set up the MongoClient with node js?

Actually, I 'm setting up the docker container of mongodb with some credentials but couldn’t be able to pass through the authentication.
UserServices.js

const { createHmac, randomBytes } = require('crypto');
const JWT = require('jsonwebtoken');
const { MongoClient } = require('mongodb');

const JWT_SECRET = '@SHLOK2003';

class UserService {
    static async connectToDatabase() {
        const client = new MongoClient('mongodb://ashlok2003:ashlok2003@127.0.0.1:27017/threads', {
            auth: {
                username: 'ashlok2003',
                password: 'ashlok2003',
            },
            authSource: 'threads',
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });

        try {
            await client.connect();
            console.log('Connected to MongoDB');
            return client.db('threads');
        }
        catch (error) {
            console.error('Error connecting to MongoDB:', error);
            throw error;
        }
    }

    static async createUser(payload) {
        const { firstName, lastName, email, password } = payload;

        const salt = randomBytes(32).toString("hex");
        const hashedPassword = UserService.generateHash(salt, password);

        const db = await UserService.connectToDatabase();
        return await db.collection("users").insertOne({ firstName, lastName, email, salt, password: hashedPassword });
    }

    

    
}

module.exports = { UserService };

Docker Compose file

version: '3.4'

services:
  mongodb:
    image: mongo:latest
    container_name: threads-mongodb
    restart: always
    ports:
      - "27017:27107"
    volumes:
      - mongodb_data:/data/db
    environment:
      - MONGO_INITDB_ROOT_USERNAME=ashlok2003
      - MONGO_INITDB_ROOT_PASSWORD=ashlok2003

  mongo-express:
    image: mongo-express:latest
    restart: always
    ports:
      - "8081:8081"
    environment:
      - ME_CONFIG_MONGODB_ADMINUSERNAME=ashlok2003
      - ME_CONFIG_MONGODB_ADMINPASSWORD=ashlok2003
      - ME_CONFIG_MONGODB_SERVER=mongodb
    depends_on:
      - mongodb

volumes:
  mongodb_data:
    driver: local

also tried using different URL’s like : - mongodb:ashlok:ashlok@localhost:27017, - mongodb:ashlok:ashlok@127.0.0.1:27017

But always end us getting authentication error ?
Please help me to overcome this problem. Thank You :+1:

Hello @SYCS06_Ashlok_Choudhary, Welcome to the MongoDB community forum,

Where is this file “UserServices.js” located?

When I see that you have added only 2 services “mongodb” and “mongo-express” in your docker-compose file.

1 Like

I have shared the content of the UserServices file above.

Hello @SYCS06_Ashlok_Choudhary,

First of all, you need to change the port sequence in the compose file, (<custom port>:<image's static port>) the first one is for the custom port that you can set yours, and the second one is port after the colon sign is MongoDB’s port.

 ports:
  # from:
  "27017:27107"
  # to: 
  "27107:27017"

So now you need to remove the existing docker-compose and build again with the updated configuration file.


Second, I think you need to specify the authSource=admin option in your connection string.

mongodb://ashlok2003:ashlok2003@127.0.0.1:27107/threads?authSource=admin

Because If we set Authentication credentials then the client will attempt to authenticate the user to the authSource database. If authSource is unspecified then the client will attempt to authenticate the user to the defaultauthdb. In your case, the connection will consider the threads database as authSource.

And if the defaultauthdb is unspecified, then it will consider admin as authSource. So you can also make the connection without specifying the database and that option like this:

mongodb://ashlok2003:ashlok2003@127.0.0.1:27107/

You can read more about authSource option in the documentation,

Still The Problem persist :sweat_smile:

Thirdly I forgot to mention that, you don’t need to pass options in MongoClient when you have already specified in the connection string,

Remove these options:

auth: {
  username: 'ashlok2003',
  password: 'ashlok2003',
},
authSource: 'threads',

If still does not work then I would suggest you connect MongoDB directly in your CMD using this mongosh command, if it is working then there is some issue in your code.

mongosh mongodb://ashlok2003:ashlok2003@127.0.0.1:27107/threads?authSource=admin

I have created docker-compose from your file after correcting the port issue and the MongoDB connection is working in my cmd using the above command.

Yuup through mongosh shell the connection is establishing i have to go through my code once again there might be some error in my code base. :+1: