Create a Local MongoDB Database and Insert a Document
This is the first post aimed at beginners in setting up a local MongoDB backend of a clocking in application. It shows the set-up and how to insert a document (data) into the database.
Firstly, if you haven’t already:
1. Download MongoDB
You can download MongoDB locally by typing into your terminal:
brew tap mongodb/brewbrew install mongodb-community
You can check if Homebrew is installed by typing:
brew help
If ‘command not found’ is returned, Homebrew can be download here: https://brew.sh/.
There are a couple reasons I choose to use a MongoDB backend over others. The lack of a schema can be forgiving when starting out with databases; during development it can allow you to see what data you are writing to the database and not be restricted by the schema. This allows mistakes to be made and to learn from it. The other big advantage is that MongoDB is scalable and adaptable for further use of the data.
2. Download Compass
Compass is an easy GUI to interact with your local DB and will allow you to bypass terminal commands for querying your DB. This is not required, but I’ll use it for the rest of the tutorial. The alternative is typing commands via the terminal, which increases the risk of mistakes being made. Compass can be downloaded here: https://www.mongodb.com/download-center/compass
3. Create Your Database
To get the DB running locally, in your terminal:
brew services start mongodb-community
Connect Compass to your local server using the connection string: mongodb://localhost
After clicking connect, click ‘CREATE DATABASE’ to create your DB. Name your database and collection appropriately, and click ‘CREATE DATABASE’:
After the database has been created, it should appear along admin, local, and config. Navigate to the new DB (‘clocking system’) you have and click on the new collection (‘staff’).
Click ‘ADD DATA’ and click on ‘Insert Document’ from the dropdown list. You can then enter in JSON format your first entry, as shown below:
The data I’ve inserted is applicable for a clocking system application, this can be any data you want, just remember to keep it in a JSON object format:
https://www.w3schools.com/js/js_json_syntax.asp
Click ‘Insert’, and there you go! You’ve created your first document in your new DB!
The next article will outline connecting the local DB you’ve just created to a React application using Express.