I'm trying to use mongodb for first time for a node.js app running on docker
This is my docker-compose file
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'
And this is my app.js file
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const connectionUrl = 'mongodb://mongo:27017';
const databaseName = 'sandbox_db';
MongoClient.connect(
connectionUrl,
{ useNewUrlParser: true },
(error, client) => {
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'
});
}
);
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?
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
Also if I docker-compose exec mongo bash I get this
docker-compose exec mongo bash
root@ashdja87a89s:/# mongo
MongoDB shell version v4.2.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("14aaa69b-8a7a-462b-ac5a-ff4ae0305d8b") }
MongoDB server version: 4.2.6
> show dbs
>
db.runCommand("connectionStatus")to see if it implicitly authenticated for you."authenticatedUsers" : [ ], "authenticatedUserRoles" : [ ]are both empty.usernameandpasswordin your mongo uri connection string, have a look here docs.mongodb.com/manual/reference/connection-stringMongoClient.connect()? and what user do I need to include, theMONGO_INITDB_ROOT_USERNAMEI use in my docker-compose file?