How to connect a Nodejs application to mongoDB | Nodejs For Total Beginners | SpreadTechAfrica Bootcamp April 2024 Part4

Chiboy
5 min readApr 24, 2024

In this tutorial, you will learn how to connect your Node.js application to a MongoDB database.

PREQUISITE
i. Have node installed in device.
ii. Have an account with MongoDB, use this https://account.mongodb.com/account/register.

WHAT IS A MONGODB DATABASE:

A MongoDB database is a NoSQL database that stores data in a flexible, JSON-like format known as BSON (Binary JSON). It is designed to handle large volumes of data and provide high performance, scalability, and flexibility. MongoDB uses a document-oriented data model, where data is stored as documents within collections rather than traditional rows and columns. This allows for easy and efficient storage of complex, hierarchical data structures, making MongoDB a popular choice for applications requiring flexible and dynamic data storage.

So lets begin.

  1. lets create a simple node express application
    i. create a simple folder in your device and call it whatever you want, mine will be my-express-app
    ii. Open the folder in VsCODE Or any code editor of your choice
    iii. Initialize the new Node.js project: Run the following command to create a package.json file:
npm init -y

iv. Install Express: Next, install the Express framework using npm:

npm i express

v. Create your main application file: Create a file named app.js in your project directory. This file will contain the code for your Express application.

// app.js
const express = require('express');
const app = express();

// Define a route
app.get('/', (req, res) => {
res.send('Hello, world!');
});

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

vi. Run your Express application: Finally, run the following command in your terminal to start your Express server:

node app.js

You should see a message indicating that the server is running. You can then open a web browser and navigate to http://localhost:3000 to see your Express application in action, displaying "Hello, world!".

Now that we have a working express application running on our server, lets connect our application to the MongoDB.

2. CONNECTING APPLICATION TO THE MONGODB

i. Register for MongoDB Atlas: MongoDB Atlas is a cloud-hosted MongoDB service. Go to the MongoDB website and sign up for an account if you don’t have one already. Follow the prompts to create your account and log in.

ii. Create a New Cluster: Once logged in, create a new cluster by clicking the “Build a Cluster” button. Choose a cloud provider, region, and cluster tier that best fits your needs. MongoDB Atlas offers a free tier suitable for development and small projects.

iii. Configure Cluster Settings: Customize your cluster settings if necessary. You can specify the cluster name, cluster tier, and other options according to your requirements. Review the configuration and click “Create Cluster” to proceed.

NOTE: what are mongoDB clusters:
MongoDB clusters are collections of servers that collaborate to store and manage data efficiently. They ensure high availability and scalability for MongoDB databases by distributing data across multiple nodes.

iv. Whitelist Your IP Address: To access your MongoDB cluster from your Express application, you need to whitelist your IP address. Go to the “Network Access” tab in your MongoDB Atlas dashboard, click “Add IP Address,” and enter your IP address or range. Alternatively, you can allow access from anywhere by adding 0.0.0.0/0 as the IP address.

v. Create a Database User: Navigate to the “Database Access” tab and click “Add New Database User.” Create a username and password for your database user and assign appropriate privileges. Make sure to remember these credentials as you’ll need them to connect to your database from your Express application.

vi. Get Connection String: After setting up your cluster and database user, MongoDB Atlas provides you with a connection string to connect to your database. Click the “Connect” button on your cluster dashboard and select “Connect your application.” Copy the connection string provided.

vii. Install MongoDB Driver for Node.js: In your Express application directory, install the Mongoose Node.js driver using npm:

npm install mongoose

3. MONGODB CONFIGURATION ON YOUR NODEJS APPLICATION

i. Create a folder called database and a new file called connetion.js so the structure will be like this database/connection.js

ii. In the connection.js file, add the following code to establish a connection to the MongoDB database using the provided connection string:

// database/connection.js


const mongoose = require('mongoose');

async function conn () {
mongoose.connect('mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority')
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});

}

conn();

NOTE: Replace <username>, <password>, <cluster>, and <database> with your MongoDB Atlas username, password, cluster URL, and database name respectively.
For security and best practice, store sensitive information such as the MongoDB connection string as environment variables in a .env file. Access these variables in your application using the dotenv package.

iii. Next you can call the function in the app.js file, so your app.js will look like this:

// app.js
const express = require('express');
const app = express();
const conn = require('./database/connection'); // import the connection function
conn // callin the function

// Define a route
app.get('/', (req, res) => {
res.send('Hello, world!');
});

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

iv. Run your Express application: Run the following command in your terminal to start your Express server:

node app

On your terminal you should be able to see your running application and connection message just like the following image:

v. Next, Go to MongoDB Dashboard: you go to your MongoDB atlas Dashboard to see the metrics of your connection:

If you have this screen then you have successfully initiated a connection from your node express application to a database called MongoDB using a Nodejs package called Mongoose

RESOURCES:

For a visual understanding, watch this YouTube video: https://youtu.be/bhiEJW5poHU?si=LTM6_cFjauel0YiG

Link to the github project: https://github.com/Prono96/spreadtechafrica_backend

Learn, how to connect a Nodejs express app to MySql database:
https://medium.com/@chiboy96/building-a-mysql-powered-express-application-a-step-by-step-guide-to-integrating-mysql-workbench-be192d32fc4e

Show me some love by ❤💛🧡💙❤
✅liking
💌subscribing
🚶‍♂️following

Thank you 🎉

ASSIGNMENT:
Learn about POSTMAN
https://youtu.be/MFxk5BZulVU?si=7ptdmQljWHiXeqNT

--

--