Creating a Web App - Part 3 : Database

  • Coding
  • Database
  • MongoDB

July 2, 2023

For my application I'm going to need to store different kind of data, that's why I need to use a database. For this app I'm going to use MongoDB. MongoDB is a NoSQL document-based database that enables you to save unstructured data in JSON-like format (the actual format ist BSON). You can download the free MongoDB Community Edition on their website here.

I already installed MongoDB and the MongoDB Shell „mongosh“ on my machine. „Mongosh“ is a command-line tool that allows you to connect to your MongoDB server and work with your data, like perform CRUD operations (Create, Read, Update, Delete), write queries, and execute administrative tasks.

To manage the object mapping between Node.js and my MongoDB database, I'm going to use an ODM (Object Data Modelling) library called Mongoose. Mongoose maps documents coming from a database into usable Javascript objects and provides ways to model out your application data and define a schema. I will go deeper into that in a later post.

Mongoose comes as an NPM package, so I will simply use the command line npm install mongoose to install it in my project. After that, I will have to require it in my app.js file:

javascript code requiring mongoose

Now I need to connect Mongoose to my MongoDB database. For now, I'm using a database that is on my local computer. Later when I go live with my application I will connect it to my MongoDB Atlas cloud database. To connect Mongoose to my local MongoDB database I will use this code (I'm using the default MongoDB port 127.0.0.1:27017 and then the name of my database, which will be "taskmanagerApp"):

javascript code connecting database

I have added the console.log to check if the connection to the database works. If I start up the server now, I get this result:

console showing connection

We get the text "Connected to MongoDB database" in the console, meaning the connection is working! Very well, now I can start creating collections and models for the various data I will need to store, but that's for a another post.