Docker, NodeJS, MongoDB auto import data

Kafka
3 min readOct 17, 2020

So I was working on a project that required me to automatically import data into my MongoDB Docker container. A lot of the tutorials online didn’t work for me or were overly complicated. So I decided to make a very simplistic solution that works.

So my project consists of a NodeJS server and MongoDB to hold the data. I want my MongoDB to auto initialize data on container startup.

Make sure you have docker installed.

SOURCE CODE: git clone && git checkout

git clone https://github.com/ottokafka/docker_nodejs_mongodb.git && git checkout mongodb_auto_import

docker-compose.yml

NodeJS Server

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const PORT = 4000;// Dont use localhost:27017 -
mongoose.connect('mongodb://database_mongodb:27017/mydb').then(() => console.log("connected to mongodb")).catch((err) => console.log(err))
// Gives user a response when visiting localhost:4000
app.get('/', function (req, res) {
res.json({ "Whats up": "world" });
});
// Starts up server and displays the port the server is running on
app.listen(PORT, function () {
console.log('Your node js server is running on PORT:', PORT);
})

MongoDB auto import script

mongoimport --db=mydb --collection=stuff --jsonArray --file=docker-entrypoint-initdb.d/data.json

This script is used in the docker-compose file. MongoDB auto executes any .sh or .js files in the docker-entrypoint-initdb.d/ directory. We already added our data to that path so we’re good to go.

data.json

Node: this data is in the form of an json array. If you have just a json use — json instead of — jsonArray

[{
"_id": "5f1580241546d8643c995ed6",
"starts_at": "22:00",
"ends_at": "23:00"
},
{
"_id": "5f1580241546d8643c995ed7",
"starts_at": "23:00",
"ends_at": "24:00"
}]

Heres what my project directory structure looks like

When were all set lets run:

docker-compose up --build
Our data was imported to mongoDB successfully
nodemon is running and connected to MongoDB

So we have our data imported into MongoDB and our Node server running ready for changes to be made to hot-reload.

I code directly into the container with Vs Code

Now I am in the container

Open the folder of my source code

Name of work directory is server

Click Ok

Changes will automatically hot-reload on save

That’s it guys. I hope you guys got something out of this article. If this article helped you go ahead and smash that clap button. Cheers 🍺

--

--

Kafka

“Genius” is 1% inspiration and 99% perspiration. Accordingly, a ‘genius’ is often merely a talented person who has done all of his homework — T.E.