0

Problem with mongo docker image and mongoose as Object Document mapper to connect to specific db after creating container:

(I made sure that DB_NAME is not undefined...)

await mongoose.connect(`${process.env.MONGO_URI}/${process.env.DB_NAME}`, {

Idk why, but whenever I try to connect to mongodb in docker container (with docker-compose built) I get this error:

error: Failed to establish MongoDB connection: MongoServerError: Authentication failed..

But when I try to connect with MongoDB Atlas without the db name just the URI, i can easily connect...

My Docker-compose file:

version: "3"
services: 
  server: 
    build: 
      context: ./server
      dockerfile: ./Dockerfile
    ports: 
      - 3001:3001
    volumes: 
      - ./server/dist:/home/nodeUser/app/dist
    depends_on: 
      - mongodb
  mongodb: 
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: toor
      MONGO_INITDB_DATABASE: auth
    ports:
      - 27017:27017

MY .env file:

PORT=3001
MONGO_URI=mongodb://root:toor@mongodb:27017/auth
DB_NAME=auth

Weirdly enough is, when I omit the credentials, so no Authentication required to connect, then it works...

I tried to omit the credentials -- login without auth required: worked I tried to connect using the same connection uri but without the db name: worked I checked if db_name could be undefined in process.env.DB_NAME: negative

1 Answers1

0

I had a similar issue. Because the user that as used was the root user, and it was not linked to a specific database. In this case, you have to add an option authSource=admin.(https://www.mongodb.com/docs/manual/reference/connection-string/#mongodb-urioption-urioption.authSource)

await mongoose.connect(`${process.env.MONGO_URI}/${process.env.DB_NAME}`, {
    //...
    authSource: "admin"
}
arnaud
  • 21
  • 3
  • Based on the question it should be rather `authSource: "auth"` or `authSource: $process.env.MONGO_INITDB_DATABASE` – Wernfried Domscheit Jul 16 '23 at 21:40
  • I tried the solution... Adding authSource with ```authSource: $process.env.MONGO_INITDB_DATABASE``` It appears still not to work... Same error as before. ``` await mongoose.connect(`mongodb://root:toor@mongodb:27017/admin`, { authSource: "admin", }); ``` – CoMpUtEr1941 Jul 16 '23 at 22:38
  • Did you import a dump ? Or did you change your docker-compose multiple times ? – arnaud Jul 17 '23 at 05:30