Connect Angular to MongoDB via Express

Connect Angular to MongoDB via Express

Building full-stack web applications involves creating a seamless connection between the frontend (client-side) and backend (server-side). In this tutorial, we’ll walk through how to connect an Angular frontend to a MongoDB database using an Express backend. This setup allows you to efficiently handle CRUD operations (Create, Read, Update, Delete) on your database, facilitating data management in real-time.

Why Use Angular, Express, and MongoDB?

When building modern web applications, a common choice is to use the MEAN stack, which stands for:

  • MongoDB: NoSQL database to store data.
  • Express: Web framework for Node.js.
  • Angular: Frontend framework for building dynamic single-page applications (SPAs).
  • Node.js: JavaScript runtime for the backend.

This combination is highly popular due to its simplicity, flexibility, and ease of use. Angular handles the user interface (UI), Express manages the backend server, and MongoDB stores data, making it a perfect choice for developing efficient full-stack applications.

Steps to Connect Angular to MongoDB via Express Backend

To demonstrate the connection between Angular and MongoDB through Express, we will create a simple web application where the frontend can send and receive data from a MongoDB database via an Express API.

Step 1: Set Up MongoDB

Before setting up your Angular and Express project, ensure you have MongoDB installed or use a cloud database service like MongoDB Atlas. For local installations, you can download MongoDB from mongodb.com.

If you opt for MongoDB Atlas, create an account and set up a cluster. You’ll receive a connection string that you will use in your Express backend to connect to the database.

Step 2: Set Up the Express Backend

To create the backend, we will use Express as the server framework and Mongoose to interact with MongoDB.

Create a new directory for your project and initialize a Node.js application:
mkdir angular-express-mongo
cd angular-express-mongo
npm init -y

Install necessary dependencies:
npm install express mongoose body-parser cors

  • Express is the web framework.
  • Mongoose is the MongoDB ORM for Node.js.
  • Body-parser helps parse incoming request bodies.
  • CORS enables cross-origin requests between Angular and Express.
Create the backend server (server.js):

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3000;

// MongoDB connection string
const dbURI = 'your-mongodb-connection-string-here';

// Connect to MongoDB
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch((err) => console.log('MongoDB connection error:', err));

// Middleware
app.use(cors());
app.use(bodyParser.json());

// Define a basic route
app.get('/', (req, res) => {
  res.send('Welcome to the Angular-Express-Mongo app!');
});

// Start server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Create a MongoDB model (models/Item.js):
const mongoose = require('mongoose');

const itemSchema = new mongoose.Schema({
  name: String,
  description: String,
  price: Number
});

const Item = mongoose.model('Item', itemSchema);

module.exports = Item;

Set up a basic API route (routes/itemRoutes.js):
const express = require('express');
const Item = require('../models/Item');
const router = express.Router();

// Create new item
router.post('/add', async (req, res) => {
  try {
    const { name, description, price } = req.body;
    const newItem = new Item({ name, description, price });
    await newItem.save();
    res.status(201).json(newItem);
  } catch (err) {
    res.status(400).json({ error: 'Error creating item' });
  }
});

// Get all items
router.get('/', async (req, res) => {
  try {
    const items = await Item.find();
    res.status(200).json(items);
  } catch (err) {
    res.status(500).json({ error: 'Error fetching items' });
  }
});

module.exports = router;

Integrate the routes in server.js:
const itemRoutes = require('./routes/itemRoutes');
app.use('/api/items', itemRoutes);

Step 3: Set Up the Angular Frontend

Create an Angular project:
ng new angular-mongo-frontend
cd angular-mongo-frontend

Install the HTTP client module to make API calls from Angular to Express:
ng generate module app-routing --flat --module=app

Generate a service to interact with the backend:
ng generate service item

Update the item.service.ts to make HTTP requests to the Express API:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ItemService {
  private apiUrl = 'http://localhost:3000/api/items';

  constructor(private http: HttpClient) {}

  // Get all items
  getItems(): Observable<any> {
    return this.http.get(this.apiUrl);
  }

  // Add new item
  addItem(item: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/add`, item);
  }
}

Create a component to display and add items:
ng generate component item-list

Update item-list.component.ts to use the ItemService:
import { Component, OnInit } from '@angular/core';
import { ItemService } from '../item.service';

@Component({
  selector: 'app-item-list',
  templateUrl: './item-list.component.html',
  styleUrls: ['./item-list.component.css']
})
export class ItemListComponent implements OnInit {
  items = [];
  newItem = { name: '', description: '', price: 0 };

  constructor(private itemService: ItemService) {}

  ngOnInit(): void {
    this.loadItems();
  }

  loadItems() {
    this.itemService.getItems().subscribe((data) => {
      this.items = data;
    });
  }

  addItem() {
    this.itemService.addItem(this.newItem).subscribe((data) => {
      this.items.push(data);
      this.newItem = { name: '', description: '', price: 0 };
    });
  }
}

Update item-list.component.html to display and add items:
<div>
  <h1>Items</h1>
  <ul>
    <li *ngFor="let item of items">{{ item.name }} - {{ item.price }}</li>
  </ul>

  <h2>Add Item</h2>
  <form (submit)="addItem()">
    <input [(ngModel)]="newItem.name" placeholder="Name" />
    <input [(ngModel)]="newItem.description" placeholder="Description" />
    <input [(ngModel)]="newItem.price" placeholder="Price" />
    <button type="submit">Add Item</button>
  </form>
</div>

Step 4: Test the Full Stack Application

Start the backend by running:
node server.js

Start the Angular frontend:
ng serve

Now, your Angular app should be able to send requests to the Express backend, which in turn communicates with the MongoDB database. You can test creating new items and fetching the existing ones via the Angular UI.

Conclusion

Connecting an Angular frontend to a MongoDB database via an Express backend creates a powerful full-stack application. This approach ensures efficient data handling, easy CRUD operations, and allows you to manage both the frontend and backend seamlessly. With Angular for the user interface and Express as the server framework, along with MongoDB for data storage, you can build secure and scalable web applications.

Post a Comment

Previous Post Next Post