title: Docker: MongoDB init script: read value from .env file
body: <p>How to read env variable in <code>mongo-init.js</code>? <code>docker-compose.yml</code> able to read from <code>.env</code> file but <code>mongo-init.js</code> can't as <code>mongo-init.js</code> will copy to <code>/docker-entrypoint-initdb.d</code> volume (not sure I'm right or wrong). This mean <code>mongo-init.js</code> will read <code>process.env.MONGODB_USERNAME</code> as <code>undefined</code>.</p>
  <p>Is it possible to convert <code>env</code> value in <code>mongo-init.js</code> first before copy to <code>/docker-entrypoint-initdb.d</code></p>
  <p>docker-compose.yml</p>
  <pre><code>version: '2'
  
  services:
    mongodb:
      image: mongo:4.4.2
      restart: always
      container_name: local-mongodb
      environment:
        MONGO_INITDB_ROOT_USERNAME: ${MONGODB_ROOT_USERNAME}
        MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_ROOT_PASSWORD}
      ports:
        - ${MONGODB_PORT}:27017
      volumes:
        - mongodb_database:/data/db
        - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js
  
  volumes:
    mongodb_data:
  </code></pre>
  <p>mongo-init.js</p>
  <pre><code>require('dotenv').config()
  
  print('mongo init start --------------------');
  
  const pms = db.getSiblingDB(process.env.MONGODB_DATABASE)
  
  pms.createUser({
    user: process.env.MONGODB_USERNAME,
    pwd: process.env.MONGODB_PASSWORD,
    roles: [
      {
        role: 'readWrite',
        db: process.env.MONGODB_DATABASE,
      },
    ],
  });
  
  print('mongo init end --------------------');
  </code></pre>
  <p>.env</p>
  <pre><code>MONGODB_ROOT_USERNAME=root
  MONGODB_ROOT_PASSWORD=password
  MONGODB_DATABASE=product
  MONGODB_USERNAME=user
  MONGODB_PASSWORD=password
  MONGODB_PORT=27017
  </code></pre>