Dario Schiraldi : Issue Connecting MongoDB with Angular - Any Suggestions?

Perhaps you can share some of the ways you tried to connect? Don’t include your user credentials - but let’s take a look at your connection string… Angular is a frontend technology so you wouldn’t connect from Angular… you’re likely going to use Node.js on the backend with something like express, dotenv and mongodb driver.

How the Full-Stack Flow Works:

  1. Angular (Frontend) → Makes API calls using HttpClient
  2. Backend (Node.js + Express) → Handles requests, interacts with MongoDB
  3. MongoDB (Database) → Stores & retrieves data

Create a server process for the backend…

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());

mongoose.connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => console.log("MongoDB Connected"))
  .catch(err => console.log(err));

app.get('/data', async (req, res) => {
    res.json({ message: "API is working!" });
});

app.listen(5000, () => console.log("Server running on port 5000"));

Create a .env file with something like…

MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority

From there you’d use http to connect to your server from the frontend.

Hope this helps.