Building the Frontend with React

Introduction

React is a JavaScript library used to build interactive, component-based user interfaces. It focuses on creating single-page applications (SPAs) where the page updates dynamically without full reloads.

React is widely used in full-stack applications and commonly paired with:

  • Node.js
  • Express.js
  • MongoDB
    (known together as the MERN stack)

Core Concepts of React Frontend

Component-Based Architecture

  • UI is broken into reusable components
  • Each component manages its own logic and view

Example:

function Header() {
  return <h1>Welcome to My App</h1>;
}

State and Props

  • Props → pass data between components
  • State → dynamic data inside a component
const [count, setCount] = useState(0);

Handling User Interaction

<button onClick={() => setCount(count + 1)}>+</button>

Fetching Data from Backend

useEffect(() => {
  fetch("/api/users")
    .then(res => res.json())
    .then(data => setUsers(data));
}, []);

Frontend Responsibilities

  • Rendering UI
  • Collecting user input
  • Sending requests to backend
  • Displaying API responses
  • Managing authentication state

Introduction to MongoDB and NoSQL Databases

What is NoSQL?

NoSQL databases are designed to store data in a flexible, non-relational format, unlike traditional SQL databases that use tables and fixed schemas.

Characteristics of NoSQL Databases

  • Schema-less or flexible schema
  • High scalability
  • Distributed architecture
  • Optimized for large datasets

What is MongoDB?

MongoDB is a document-oriented NoSQL database that stores data in JSON-like documents (BSON).

Why MongoDB is popular:

  • Easy to use with JavaScript
  • Flexible schema
  • High performance
  • Cloud-ready
  • Ideal for modern web apps

MongoDB Data Model: Collections and Documents

Database

A database is a container for collections.

Example:

ecommerce_db

Collections

A collection is a group of related documents (similar to a table in SQL).

Example:

users
orders
products

Documents

A document is a single record stored as a JSON object.

Example:

{
  "_id": "123",
  "name": "Alice",
  "email": "alice@example.com",
  "age": 25
}

Key Features

  • Fields can vary between documents
  • Nested structures allowed
  • Each document has a unique _id

Embedded Documents

{
  "name": "Order1",
  "items": [
    { "product": "Laptop", "price": 800 }
  ]
}

CRUD Operations in MongoDB

CRUD = Create, Read, Update, Delete


Create (Insert Documents)

Insert One

db.users.insertOne({ name: "John", age: 30 })

Insert Many

db.users.insertMany([
  { name: "Alice" },
  { name: "Bob" }
])

Read (Query Documents)

Find All

db.users.find()

Find with Condition

db.users.find({ age: { $gt: 25 } })

Update Documents

Update One

db.users.updateOne(
  { name: "John" },
  { $set: { age: 31 } }
)

Update Many

db.users.updateMany(
  { age: { $lt: 18 } },
  { $set: { status: "minor" } }
)

Delete Documents

Delete One

db.users.deleteOne({ name: "John" })

Delete Many

db.users.deleteMany({ age: { $lt: 18 } })

Indexing, Aggregation, and Querying Data

Indexing in MongoDB

Indexes improve query performance by allowing fast data lookup.

Create Index

db.users.createIndex({ email: 1 })

Types of Indexes

  • Single field
  • Compound
  • Text index
  • Unique index

Querying Data

MongoDB supports powerful query operators:

OperatorPurpose
$gtGreater than
$ltLess than
$inMatch multiple values
$and, $orLogical conditions

Example:

db.users.find({ age: { $gte: 18, $lte: 30 } })

Aggregation Framework

Used for data processing and analysis.

Aggregation Pipeline Stages

  • $match – filter documents
  • $group – group data
  • $sort – sort results
  • $project – reshape output

Example:

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$userId", total: { $sum: "$amount" } } }
])

Working with MongoDB Atlas (Cloud Database)

What is MongoDB Atlas?

MongoDB Atlas is a fully managed cloud database service for MongoDB.

Key benefits:

  • No server maintenance
  • Automatic backups
  • Built-in security
  • Global availability
  • Scales easily

Steps to Use MongoDB Atlas

1. Create an Atlas Account


2. Create a Cluster

  • Choose cloud provider (AWS/GCP/Azure)
  • Select region
  • Use free tier for learning

3. Configure Security

  • Create database user
  • Whitelist IP address
  • Enable authentication

4. Get Connection String

mongodb+srv://username:password@cluster.mongodb.net/dbname

5. Connect from Node.js

import mongoose from "mongoose";

mongoose.connect(process.env.MONGO_URI)
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.error(err));

Atlas Features

  • Performance monitoring
  • Data Explorer
  • Automated scaling
  • Backup and restore
  • Alerts and logs

React + MongoDB in a Full-Stack App

Data Flow

React UI → Express API → MongoDB → Express → React

Example:

  • React form submits data
  • Express receives request
  • MongoDB stores document
  • Response sent back to React
  • UI updates

Best Practices

  • Validate data before inserting
  • Use indexes for frequent queries
  • Never expose MongoDB credentials in frontend
  • Use environment variables
  • Secure Atlas access properly

Summary

  • React handles frontend UI and user interaction
  • MongoDB stores flexible, scalable data
  • CRUD operations manage data lifecycle
  • Indexing and aggregation optimize performance
  • MongoDB Atlas enables cloud-based deployment
  • Together they form the foundation of modern full-stack applications

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *