Connecting Angular Frontend to MongoDB via Express Backend

MongoDB With Angular Sample

Connecting MongoDB with an Express backend and an Angular frontend involves several steps. Here's a detailed guide, including a code sample, input/output, and steps.

Step 1. Set Up MongoDB

  1. Install MongoDB
    • Install MongoDB locally or use a cloud solution like MongoDB Atlas.
    • Start the MongoDB server.
  2. Create a Database
    • Use the MongoDB shell or a GUI tool like MongoDB Compass to create a database, e.g., my_database.
    • Add a collection, e.g., users.

Step 2. Create an Express Backend

Initialize the Project

mkdir express-mongodb-app
cd express-mongodb-app
npm init -y
npm install express mongoose body-parser cors

Create the Server File: Create a file named server.js.

javascript

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

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

// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/my_database', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => console.log("MongoDB connected"))
  .catch(err => console.error(err));

// Define Schema and Model
const userSchema = new mongoose.Schema({
    name: String,
    email: String,
});
const User = mongoose.model('User', userSchema);
// Routes
app.get('/api/users', async (req, res) => {
    const users = await User.find();
    res.json(users);
});
app.post('/api/users', async (req, res) => {
    const newUser = new User(req.body);
    await newUser.save();
    res.status(201).json(newUser);
});
// Start Server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

Run the Server

node server.js

Step 3. Create the Angular Frontend

Set Up Angular Project

ng new angular-mongodb-app
cd angular-mongodb-app
ng add @angular/material
npm install axios

Service for API Communication: Create a file src/app/services/user.service.ts.

typescript

import { Injectable } from '@angular/core';
import axios from 'axios';
@Injectable({
    providedIn: 'root'
})
export class UserService {
    private baseUrl = 'http://localhost:3000/api/users';
    getUsers() {
        return axios.get(this.baseUrl);
    }
    addUser(user: { name: string; email: string }) {
        return axios.post(this.baseUrl, user);
    }
}

Component for User Interaction: Update src/app/app.component.ts.

typescript

import { Component, OnInit } from '@angular/core';
import { UserService } from './services/user.service';

@Component({
    selector: 'app-root',
    template: `
        <div style="text-align: center;">
            <h1>Angular with Express & MongoDB</h1>
            <form (submit)="addUser($event)">
                <input type="text" [(ngModel)]="name" placeholder="Name" name="name" required>
                <input type="email" [(ngModel)]="email" placeholder="Email" name="email" required>
                <button type="submit">Add User</button>
            </form>
            <ul>
                <li *ngFor="let user of users">{{ user.name }} ({{ user.email }})</li>
            </ul>
        </div>
    `,
    styles: []
})
export class AppComponent implements OnInit {
    users: any[] = [];
    name = '';
    email = '';

    constructor(private userService: UserService) {}

    ngOnInit() {
        this.loadUsers();
    }

    async loadUsers() {
        const response = await this.userService.getUsers();
        this.users = response.data;
    }

    async addUser(event: Event) {
        event.preventDefault();
        await this.userService.addUser({ name: this.name, email: this.email });
        this.loadUsers();
        this.name = '';
        this.email = '';
    }
}

Install Angular Forms Module: Add FormsModule to AppModule.

typescript

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule, FormsModule],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}

Run the Angular Application

ng serve

Step 4. Input and Output

Input

Output: The list below the form will update to include the newly added user.

less

Uma Rani ([email protected])

Step 5. Visual Workflow (Images)

Backend (server.js)

  1. Database schema for storing user data.
  2. APIs (/api/users) for CRUD operations.

Frontend (Angular App)

  1. The user fills out the form.
  2. Data is sent to the Express backend.
  3. Data is saved in MongoDB.
  4. Users are displayed dynamically.