The problem is with mongo's authentication. If you define an administrator user and another user with only read and write permissions on the database, this problem is solved:
To set the admin user, simply set the following mongo environment variables:
MONGO_INITDB_ROOT_USERNAME=username_for_admin
MONGO_INITDB_ROOT_PASSWORD=password_for_admin
MONGO_INITDB_DATABASE=database_name
To define the other user define the following variables:
MONGO_URL=mongo:27017
MONGO_DB=database_name
MONGO_USERNAME=username_for_normal_user
MONGO_PASSWORD=password_for_normal_user
After that, just create the following script to add the user when mongo is started:
#!/bin/bash
set -e
mongo <<EOF
use admin
db.createUser({
user: '$MONGO_USERNAME',
pwd: '$MONGO_PASSWORD',
roles: [{
role: 'readWrite',
db: 'database_name'
}]
})
EOF
When you connect to the database, put the user in the mongo url, like this (if it is javascript or typescript it is exactly this):
mongo://${process.env.MONGO_USERNAME}:${process.env.MONGO_PASSWORD}@${process.env.MONGO_URL}/${process.env.MONGO_DB}?authSource=admin
Finally, you have to go to the mongo.conf file and add the following fields:
# mongod.conf
#(...)
security:
authorization: "enabled"
#(...)