title: Docker mongo - MongoError: command insert requires authentication
body: <p>I'm trying to use mongodb for first time for a node.js app running on docker</p>
  
  <p>This is my docker-compose file</p>
  
  <pre><code>version: '3'
  
  services:
      nodejs:
          container_name: sandbox_app
          build:
              context: .
              dockerfile: Dockerfile
          ports:
              - '3000:3000'
          volumes:
              - '.:/usr/src/app'
              - '/usr/src/app/node_modules'
          networks:
              - sandboxnet
          links:
              - mongo
      mongo:
          image: mongo
          container_name: sandbox_db
          # restart: always
          ports:
              - '27017:27017'
          environment:
              MONGO_INITDB_ROOT_USERNAME: root
              MONGO_INITDB_ROOT_PASSWORD: example
          networks:
              - sandboxnet
      mongo-express:
          image: mongo-express
          # restart: always
          ports:
              - 8081:8081
          environment:
              ME_CONFIG_MONGODB_ADMINUSERNAME: root
              ME_CONFIG_MONGODB_ADMINPASSWORD: example
          depends_on:
              - mongo
          networks:
              - sandboxnet
  
  volumes:
      node_modules:
      web-root:
          driver: local
  networks:
      sandboxnet:
          driver: 'bridge'
  </code></pre>
  
  <p>And this is my app.js file</p>
  
  <pre><code>const mongodb = require('mongodb');
  const MongoClient = mongodb.MongoClient;
  
  const connectionUrl = 'mongodb://mongo:27017';
  const databaseName = 'sandbox_db';
  
  MongoClient.connect(
      connectionUrl,
      { useNewUrlParser: true },
      (error, client) =&gt; {
          if (error) {
              return console.log('Unable to connect to the database :(');
          }
  
          console.log('Connected succesfully to mongo :)');
          const db = client.db(databaseName);
  
          db.collection('users').insertOne({
              name: 'John Doe'
          });
      }
  );
  </code></pre>
  
  <p>when I run docker-compose up I get the following error from mongo on the terminal and can't see the new database created neither the users table or the record added. How can I fix this?</p>
  
  <pre><code>sandbox_app | Connected succesfully to mongo :)  // So skips the first console.log as there are no connection errors
  sandbox_app | (node:80) UnhandledPromiseRejectionWarning: MongoError: command insert requires authentication
  </code></pre>
  
  <p>Also if I <code>docker-compose exec mongo bash</code> I get this</p>
  
  <pre><code>docker-compose exec mongo bash
  root@ashdja87a89s:/# mongo
  MongoDB shell version v4.2.6
  connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
  Implicit session: session { "id" : UUID("14aaa69b-8a7a-462b-ac5a-ff4ae0305d8b") }
  MongoDB server version: 4.2.6
  &gt; show dbs
  &gt; 
  </code></pre>