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