I can't connect to my docker monogodb from my nodejs using mongoose

Viewed 20

I created an Image of mongodb and mongo-express and mongo-express was able to connect to mongodb

but I am trying to connect to mongodb from nodejs but I am getting error

MongoServerError: Authentication failed.
    at Connection.onMessage (/home/oshabz/Desktop/booking app/server/node_modules/mongodb/lib/cmap/connection.js:210:30)
    at MessageStream.<anonymous> (/home/oshabz/Desktop/booking app/server/node_modules/mongodb/lib/cmap/connection.js:63:60)

docker-compose.yaml

version: '3'
services:
  mongodb:
    image: mongo
    ports:
      - 27017:27017
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=password
  mongo-express:
    image: mongo-express
    ports:
      - 8081:8081
    environment:
      - ME_CONFIG_MONGODB_ADMINUSERNAME=admin
      - ME_CONFIG_MONGODB_ADMINPASSWORD=password
      - ME_CONFIG_MONGODB_SERVER=mongodb
    depends_on:
      - mongodb

Mongoose connection String

MONGO="mongodb://admin:password@localhost:27017/test_db"

I am using mongoose and if I remove test_db from the connection url it connects to mongodb but not to any database.

How do I specify my database if I remove it from the url?

1 Answers

You can refer to the mongodb container by the DNS name mongodb from within the mongo-express (client) container. Docker automatically resolves the name to the container with a little bit of magic.

Then you can use mongodb instead of localhost in the connection string.

Within the mongo-express container, localhost refers to itself, not the mongodb container, and not the host.

Change:

MONGO="mongodb://admin:password@localhost:27017/test_db"

to:

MONGO="mongodb://admin:password@mongodb:27017/test_db"
Related