Small Project with React JS, Express/Node.js, and MongoDB Database

Abstract: Resolve Mongoose deprecation warnings and CORS errors by configuring a secure Express backend with modern connection strings and environment variables.

Created: 2026-09-29 by
Building a full-stack application with React, Express, Node.js, and MongoDB is the standard way to create scalable web services. This guide provides a complete, modern setup using current best practices for Mongoose connection strings and secure server configuration. You will learn how to structure the backend API, connect to MongoDB Atlas without deprecated options, and fetch data in a React frontend to display dynamic content effectively.

Project Architecture Overview

The MEAN stack (MongoDB, Express, Angular/React, Node) separates concerns clearly. The database stores persistent data, the backend handles business logic and HTTP requests, and the frontend manages the user interface. For this small project, we will create a simple task manager that allows users to add, view, and delete tasks. This architecture ensures that the frontend remains lightweight while the backend handles data validation and storage. Using separate ports for development avoids CORS issues during local testing, which is a common pitfall for beginners.

Setting Up the Backend Server

First, initialize the backend directory and install the necessary dependencies. Run npm init -y followed by npm install express mongoose cors dotenv. Create a file named server.js to serve as the entry point. Modern versions of Mongoose no longer require the useNewUrlParser or useUnifiedTopology options, as they are enabled by default. Including them now triggers deprecation warnings. Instead, pass the connection string directly to mongoose.connect().
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();

const app = express();
app.use(express.json());
app.use(cors());

// Connect to MongoDB using environment variables
mongoose.connect(process.env.MONGO_URI)
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.error(err));

app.listen(5000, () => {
  console.log('Server running on port 5000');
});
This code sets up an Express server that listens on port 5000. It uses the cors middleware to allow requests from your React frontend, typically running on port 3000. The dotenv package loads environment variables from a .env file, keeping sensitive data like your MongoDB URI out of version control. Always store your connection string in MONGO_URI within your environment file.

Creating the Data Model

Define a Mongoose schema to represent your data. For a task manager, each task needs a title and a completion status. Create a folder named models and inside it, a file called Task.js. Schemas enforce structure and provide built-in validation.
const mongoose = require('mongoose');

const taskSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    trim: true
  },
  completed: {
    type: Boolean,
    default: false
  }
}, {
  timestamps: true
});

module.exports = mongoose.model('Task', taskSchema);
The timestamps: true option automatically adds createdAt and updatedAt fields to every document. This is useful for auditing and sorting. By exporting the model, you can import it into your route files. This separation keeps your code modular and easy to test.

Implementing API Routes

Create a routes folder with a tasks.js file. Here, you define endpoints for CRUD operations. Use async/await to handle database promises cleanly.
const express = require('express');
const router = express.Router();
const Task = require('../models/Task');

// Get all tasks
router.get('/', async (req, res) => {
  try {
    const tasks = await Task.find();
    res.json(tasks);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Add a new task
router.post('/', async (req, res) => {
  const task = new Task({
    title: req.body.title
  });
  try {
    const newTask = await task.save();
    res.status(201).json(newTask);
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

module.exports = router;
In server.js, include these routes using app.use('/api/tasks', tasksRoutes). This prefixes all task-related endpoints with /api/tasks, preventing conflicts with other potential routes. Always wrap database calls in try/catch blocks to handle errors gracefully and return appropriate HTTP status codes.

Building the React Frontend

Generate a React app using npx create-react-app client. Install Axios for HTTP requests: npm install axios. In src/App.js, use the useEffect hook to fetch data when the component mounts.
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [tasks, setTasks] = useState([]);
  const [title, setTitle] = useState('');

  useEffect(() => {
    fetchTasks();
  }, []);

  const fetchTasks = async () => {
    const res = await axios.get('http://localhost:5000/api/tasks');
    setTasks(res.data);
  };

  const addTask = async () => {
    await axios.post('http://localhost:5000/api/tasks', { title });
    fetchTasks();
    setTitle('');
  };

  return (
    
setTitle(e.target.value)} />
    {tasks.map(task =>
  • {task.title}
  • )}
); } export default App;
This component maintains state for the list of tasks and the input field. When the user clicks "Add", it sends a POST request to the backend. The backend saves the task and returns the new object, which triggers a refetch to update the UI. This pattern ensures the frontend always reflects the current database state.

Running the Application

Start the backend with node server.js and the frontend with npm start in the client directory. Ensure your MongoDB Atlas cluster is accessible from your IP address. If you encounter connection issues, check your network settings and firewall rules. For more details on handling specific database errors, see Troubleshooting BSON Type to Date Conversion in MongoDB.

Frequently Asked Questions

Why am I getting a CORS error?

CORS errors occur because browsers block requests from one origin to another for security. Ensure the cors middleware is installed and applied in your Express server before defining routes. You can also configure specific origins if needed.

How do I deploy this full-stack app?

You can deploy the backend on Heroku or Render and the frontend on Vercel or Netlify. Set the MONGO_URI environment variable in your deployment platform's dashboard. Update the frontend API URLs to point to the production backend endpoint.

Can I use TypeScript instead of JavaScript?

Yes, both React and Express support TypeScript natively. You would need to install type definitions for Express and Mongoose using @types/express and @types/mongoose. Define interfaces for your models to get compile-time checking.

What happens if the database connection fails?

If mongoose.connect rejects, the server should log the error and potentially exit. In production, implement a retry mechanism or health checks. Use process.on('unhandledRejection') to catch any unhandled promise rejections during startup.

How do I handle authentication in this setup?

Add a JWT library like jsonwebtoken and bcryptjs. Hash passwords before saving them to the database. After login, generate a token and send it to the client. Verify the token on protected routes using middleware that reads the Authorization header.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More