I'm trying to run a single mongodb instance in replica set mode to enable the use of transactions.
I have the following docker-compose.yml:
version: "3.7"
services:
mongo:
container_name: mongo-database
image: mongo:6.0.4
restart: unless-stopped
env_file:
- .env
ports:
- "27017:27017"
volumes:
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js
hostname: localhost
networks:
- mongo-network
command: ["--replSet", "rs0"]
networks:
mongo-network:
external: true
And here is the mongo-init.js
file:
rs.initiate({ _id: 'rs0', members: [{ _id: 0, host: 'localhost:27017' }] })
db = db.getSiblingDB('mydb')
db.createUser({
user: 'dev',
pwd: 'dev',
roles: [{ role: 'root', db: 'mydb' }]
})
The docker image runs fine and I have no error message in the logs.
But I'm unable to connect to the database using mongoose or any mongodb client. I got an authentication error and there is the following error message in the mongo's logs:
mongo-database | {"t":{"$date":"2023-03-20T14:44:41.072+00:00"},"s":"I", "c":"ACCESS", "id":20249, "ctx":"conn62","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-1","speculative":false,"principalName":"dev","authenticationDatabase":"mydb","remote":"172.22.0.1:47208","extraInfo":{},"error":"UserNotFound: Could not find user \"dev\" for db \"mydb\""}}
I'm using the URI mongodb://localhost:27017/mydb?replicaSet=rs0
with dev
and dev
as login and password.
What am I doing wrong?