What's the best way to initialize databases in compose?

I’m running a docker compose stack locally, and I need to initialize some users in Mongo when the database starts up. I’m doing it with the following:

mongo_init:
image: mongodb/mongodb-community-server:latest
command: mongosh mongodb://mongodb/ -u root -p password --eval “use logs” --eval “if (db.getUser(‘logs’) != null) { db.dropUser(‘logs’) }” --eval “db.createUser({user:‘logs’, pwd:‘password’, roles:[{role:‘readWrite’,db:‘logs’}]})”
env_file:
- ./secrets/mongo.local.env
depends_on:
- mongodb

… and that’s working fine. The problem is that I have the password for both the mongo db instance and the logs user defined in ./secrets/mongo.local.env and I don’t know how to reference them in the command.

Is this the best approach to the problem? Should I be doing something else?

Try something like

services:
  mongo_init:
    image: mongodb/mongodb-community-server:latest
    command: >
      mongosh mongodb://mongodb/ 
      -u $MONGO_INITDB_ROOT_USERNAME 
      -p $MONGO_INITDB_ROOT_PASSWORD 
      --eval "use logs" 
      --eval "if (db.getUser('logs') != null) { db.dropUser('logs') }" 
      --eval "db.createUser({user:'logs', pwd:'$LOGS_USER_PASSWORD', roles:[{role:'readWrite', db:'logs'}]})"
    env_file:
      - ./secrets/mongo.local.env
    depends_on:
      - mongodb