Getting Started with Mongoose and streamlining Node.js Development with Nodemon: A Beginner's Guide to Building a Basic Web Application with MongoDB

In this post of our series, we will dive deeper into utilizing development tools such as Nodemon and integrating a MongoDB database with the help of Mongoose. Nodemon is a must-have tool for any developer, it automatically restarts the application when changes are detected in the directory, saving a lot of time and effort. Furthermore, we'll explore MongoDB, a widely-used and powerful NoSQL database, and how to connect to it using Mongoose, a popular MongoDB object modelling tool.

Step 1: Installing Nodemon and Mongoose

To use Nodemon and Mongoose in your Express.js application, you'll first need to install them. Open your terminal and navigate to your project's root directory. Then, run the following commands:

npm install --save-dev nodemon

This command installs Nodemon as a development dependency, which means it will only be installed on your local machine and not on the production server.

npm install mongoose

Step 2: Using Nodemon

Once Nodemon is installed, you can use it to run your Express.js application. In your package.json file, you'll need to update the "start" script to use Nodemon. The "start" script is the command that runs when you type "npm start" in your terminal. Update the "start" script to the following:

"start": "nodemon server.js"

This tells Nodemon to run the "server.js" file. Now, when you run "npm start" in your terminal, Nodemon will automatically restart your server whenever changes are detected in your project's files. Your package.json file should look something like this:

{
  "name": "app-name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "mongoose": "^6.8.3"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

Step 3: Creating a .env file

To create a .env file, we first need to create a folder called "configs" in our project's root directory. Inside the "configs" folder, create a new file named ".env" (note the leading dot). This file will store our environment variables, which are variables that are specific to the environment in which our application is running.
If you are using version control like git remember to put your .env file in the gitignore file as it will store sensitive information.

Step 4: Configuring the .env file

Now that we have our .env file created, we can start adding variables to it. For our Express.js application, we'll need to add a variable for the MongoDB connection string. The connection string is a URI that tells MongoDB how to connect to our database. It should look something like this: mongodb://localhost:27017/database_name. Add this variable to your .env file with the following format:

MONGO_CONNECTION_STRING=mongodb://localhost:27017/database_name

At this point, you should also install the dotenv package so that you can access the variables that you put in your .env file.
You can do that by running the command below:

npm install dotenv

Step 5: Connecting to MongoDB

Now that we have our MongoDB connection string stored in our .env file, we can use it to connect to our database. To keep our server.js file clean and organized, we'll create a new file called db.js in a folder called "db". Inside the db.js file, we'll handle the connection to our MongoDB database.

We'll be using Mongoose, a MongoDB object modelling tool, to help us interact with our database in a more organized and structured way. To connect to our database, we'll need to require Mongoose at the top of our db.js file, and then call the connect() method, passing in our MongoDB connection string.

Here's an example of how to connect to MongoDB using Mongoose in the db.js file:

const mongoose = require('mongoose');
require('dotenv').config({path : '.env'});

mongoose.connect(process.env.MONGO_CONNECTION_STRING, { useNewUrlParser: true, useUnifiedTopology: true});

const db = mongoose.connection;

db.on('connected', () => {
    console.log(`Connected to MongoDB at ${process.env.MONGO_CONNECTION_STRING}`);
});

db.on('disconnected', () => {
    console.log(`Disconnected from MongoDB at ${process.env.MONGO_CONNECTION_STRING}`);
});

db.on('error', (error) => {
    console.log(`Error connecting to MongoDB: ${error}`);
});

module.exports = db;

In this example, we are logging the connection, disconnection and error events to the console for debugging purposes.

Step 6: Connecting to the Database after the Server has started listening

To ensure that our server is entirely up and running before connecting to the database, we'll need to make some modifications to our server.js file.

First, we'll need to import the db.js file and call the exported function to connect to the db. Next, we'll need to start the server using the app.listen() method, passing in the desired port and a callback function. Inside the callback function, we'll add a call to the exported function from db.js file, which will open the connection to the MongoDB database. It should look something like this:

const express = require('express')
const app = express()
const port = 3000
require('./db/db');

app.use(express.static(__dirname + '/public'))

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html')
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`)
});

Once the server starts listening, the callback function is executed, which logs a message to the console that the server The connection to the MongoDB database is handled by the mongoose.connect() function in the db.js file

That's it! Now your application is connected to a local MongoDB database using and you have a clean and organized way of handling the connection.

In the next post, we will continue exploring how to interact with our MongoDB database by learning about CRUD (Create, Read, Update, and Delete) operations. We will learn how to use Mongoose to create models, validate data, and perform basic CRUD operations on our database collections. We will also look at some best practices for working with MongoDB and Mongoose in a real-world application. This post will be a great next step for those who have followed this series and have a basic understanding of connecting to a MongoDB database with Express.js and Mongoose.