Using MongoDB with ExpressJS - Part 1 (Setting Up Express)

Using MongoDB with ExpressJS - Part 1 (Setting Up Express)

Power-packed Express with MongoDB for solid Backend Service

This would be a detailed article on how MongoDB can be used with express to make a full-fledged backend service and serve any frontend application.

MongoDB Atlas makes it very useful to connect to a database and perform operations on it! First of all, let us go through some basic setup for express. Follow the below steps to set up an express server.

ExpressJS Setup:-

  1. Type npm init in the terminal to have the package.json file setup.
  2. Type npm install express nodemon to have express installed and nodemon helps to refresh the server rather than to stop and run again.
  3. Now just go to the package.json file and in scripts clear everything and type a start command:- "start": "nodemon app.js"
  4. Now make an app.js file where all your express app will reside
  5. Add these lines of code given below for initializing the app.
const express = require('express');
const app = express();

app.listen(3000);

Now after initialization, we can now make routes have some URL. Let me show an example of an URL in express:-

app.get('/',(req,res)=>{
     res.send("hello world");
})

We can make the routes as these and have different functions as needed. As we are building a crud app we can have a post, add, delete, and update URLs for the express app. Before moving to URLs, one thing I want to stress upon is the as we have written above app.get above we have more such methods like:=

  1. app.get - to get any information, can be used when retrieving the data from the database
  2. app.post - to post any information, can be used when we insert some data in the database
  3. app.delete - when we want to delete some stuff in the database
  4. app.patch - to update the data in the database

Now let's make some basic routes and add in the express app!

app.get('/retrieve',(req,res)=>{
     res.send("We will retrieve data from this URL");
app.post('/add',(req,res)=>{
     res.send("Add the data");
app.delete('/del',(req,res)=>{
     res.send("delete the data");
app.patch('/update',(req,res)=>{
     res.send("Update");

Now we have finished setting up the express server. You can just spin the server using the command npm start and hit the routes at localhost:3000/{URL} where URL can be any route we have defined in the above app.js file.