TutorialsDSAData ScienceWeb TechCourses oS
MERN Stack MERN Interview Questions MERN Projects MERNStackDeveloper ReactJS React Interview Q
Address Book using MERN
Last Updated : 15 Nov, 2023,
In this article, we will build a Address Book using the MERN stack. The
application will enable users to add, remove, edit and view addresses. The
project will use the mongoDB database for storage and React for UI part.
This classic address book helps you to save your contacts easily and data
can be retrieved easily.
Preview of Final Output: Let us have a look at how our final project will
look like:
Address Book
Name: GeetaForGeeke
Ema: efg@emallcom
Contact: 1234567890
‘Adress fg, noida, india
nu
Name txt
Email: [email protected]
Contact 123154352
Address: test, tet, test
ae
Prerequisites of Address Book :
* Model schema for address should be designed before implementing the
database .
* The routes and endpoints of NodeJS backend must be designed before
implementation
Technologies Used in Address Book:
* MongoDB
* Express
¢ React JS
* NodeJS
Approach To create Address Book:1. We will build a frontend in React that will use bootstrap to develop a UI
which will be used for below mentioned functionalities .
2. Then we will create MongoDB collection to store the data related to
addresses .
3. NodeJS will be used for developing backend server and Express will be
used to implement endpoints used by our frontend
ies of Address Book :
The project will have following functionalities .
Functiona
+ Add Address : User can create a new address and save it to address book
* Remove Address : User can remove existing addresses from address book.
* Edit Address : User can edit and update existing address.
* View Addresses : User can view all the addresses from address book.
Steps to create a Address Book :
FrontendStep 1: First we will create a frontend for our application in React . start a
new react project using below command
nox create-react-app address-book
Step 2: For this project we will require axios to make API calls to backend .
Also we will require bootstrap for elegant design . We are also going to use
react-bootstrap-icons for icons . finally we will use react-router-dom
package for routing in frontend.
Step 3: Install all the dependencies using npm as below inside frontend
folder,
nom i axios react-bootstrap-icons react-router-dom
Step 4: For bootstrap get CDN links of bootstrap and jquery and paste it
inside index.html file in public folder as below,
tink
href="https://cdn jsdelivr.net/npm/[email protected]/dist/ess/bootstrap.mi
n.css” re
'stylesheet” integrity="sha384-
EVSTQN3/azprG.1Anm3QDgp/LIm9Nao0Yz1ztcQTwFspd3yD65Vohhpu
uCOmLASJC" crossorigin="anonymous">
integrity=
Step 5: Create a folder called components in src directory and create files.
AddAddress,js, AddressListjs, Navigation,js inside it.
Backend
For backend create a separate folder outside of React folder called ‘address-
book-backend’.Ae ae) di
AREPA
Step 1: Inside this folder initiate node project using below command.
npm init
Step 2: Now lets install required packages nodemon , express , mongoose ,
cors , body-parser as below
npm i express nodemon mongoose cors body-parser
Step 3: Once the packages are installed create a app,js file which will contain
our backend code . Also create a folder models and create a file addressjs
Database :
* For database we are using local MongoDB you can use Atlas also .
* Inside MongoDB create a new database with the name ‘addressbook’
* Now create ‘addresses’ collection inside this database and we are done
with database part.
Project Structure of Address Book:The updated dependencies in package,json will look like:
Frontend :
"dependencies": {
"@testing-library/jest-dom": "5.17.8",
"@testing-library/react": "*13.4.8",
"@testing-library/user-event": "913.5.8",
"axios": "41.5.1",
"http": "90.0,1-security",
“react": "18.2.8"
“peact-bootstrap-icons": "41.18.3",
“react-dom": "*18.2.8",
"46.16.80";
“react-scripts": "5.0.1",
"web-vitals": "42.1.4"
}
Backend:
"dependencies": {
“body-parser": "41,28.2",
"cors": "92.8.5",
express": "4.18.2",
"mongoose": "7.6.8",
"nodemon": "43.8.1
}
Example: Write the following code in respective file
Frontend Code :
* App,js: This file implements routing and imports all components
+ AddAddress.js: This component creates a forma to save new addresses
* AddressListj: This component displays Address in a list format
* Navigation
: This component implements navigation and handle update
and delete function
Javascript
J1pp.js
import React from ‘react’;
import { BrowserRouter as Router, Route, Routes } from ‘react-router-dom’ ;
import AddressList from './components/AddressList’;
import Addaddress from '../components/AddAddress’ ;function App() {
return (
{
nav("/')5
Yi:
¥
return (
Add Address
< Navigation />
vy
{addresses.map((address) => (
container d-flex flex-row m-3'>export default Navigation;
Backend Code :
* app.is: This file creates a connection between backend and frontend
* address,js: This file creates a schema for saving data in database.
Javascript
Happ.3s
const express = require( express’);
const mongoose = require(‘mongoose');
const bodyParser = require( body-parser’);
const cors = require('cors');
const app = express()3
//bodyparser used for parsing request body
app.use(bodyParser.urlencoded({ extended: false }));
app-use(bodyParser.json());
app.use(cors());
mongoose. connect ( ‘nongodb://127.0.0.1:27617/addressbook' );
const Address = require('./models/address');
/1Get route for fetching addresses from database
app.get('/api/addresses", async (req, res) => {
try {
const addresses = await Address. find();
res. json(addresses);
} catch (err) ¢
res. status(5@@).Json({ error: err.message })3
+
Ds
//Post route for storing new address
app.post('/api/addresses', async (req, res) => {
try {
const newAddress = new Address(req. body) ;
const savedAddress = await newAddress.save();
res.status(201).json(savedAddress) 5
} catch (err) {
res.status(400).json({ error: err.message });
+
Ds
//Put route For updating address with new data
app.put('/api/addresses/:id', async (req, res) => {
try {
const updatedAddress = await Address. findByTdandUpdate(req.params.id,
req. body,
{ new: true }
uw
res. json(updatedAddress) ;
} catch (err) {
res. status(400).json({ error: err.message });
3
v3
//oelete route for deleting address with specified id
app.delete('/api/addresses/:id', async (req, res) => {
try {
await Address. FindByTdAndRexove( req. params. id) ;
res.json({ message: ‘Address deleted’ });
} catch (err) {
res. status(500).json({ error: err.message });
}
Ds
const PORT = 50003
app.listen(PORT, () => ¢
console. log("Server is started on port ${PORT}”);
v3
Javascript
/Taddeess. js
const mongoose = require('mongoose');
//address schema for storing address
const addressSchena = new mongoose. Schema({
name: String,
email: String,
contact: String,
address : String
v3
module.exports = mongoose.model('Address', addressSchema , ‘addresses');
Steps to run the application :
Steps for running frontend code :
Step 1: Open terminal inside frontend folder and run below command
nom start
Step 2: The browser will automatically open tab with home page.
Steps for running backend code :Step 1: For running application first lets add start script inside package,json
of backend. add line for nodemon start script.
"scripts": {
“test
cho \"Error: no test specified\" && exit 1",
‘nodemon app. js"
Step 2: Open another terminal inside backend folder and run below
command,
nom start
Output :
Address Book
b
Name GesksForGeks
Email: gfosemsitcom
Contact 1234567099,
Address: fa, nod, nia
ae
The saved data in database will look like:
wid: Objectid('65300eafafo7c8fe823046d5' )
name: "Shobhit Sharma"
email
"[email protected]"
contact: "7894561236"
address: "sdcsd"
Want to be a Software Developer or a Working Professional looking to
enhance your Software Development Skills? Then, master the concepts of
Full-Stack Development. Our Full Stack Development - React and Node.js
Course will help you achieve this quickly. Learn everything from Front-End