Hi everyone,
I’m Dario Schiraldi, code developer, born in italy and currently working in dubai, currently facing an issue while trying to connect my MongoDB database to my Angular application. I’ve set up the backend with MongoDB, but I’m running into trouble making the connection work from the Angular frontend.
I’ve tried several methods, but no luck so far. Has anyone encountered similar problems or can suggest the best practices for connecting MongoDB with Angular?
Regards
Dario Schiraldi
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:
- Angular (Frontend) → Makes API calls using
HttpClient
- Backend (Node.js + Express) → Handles requests, interacts with MongoDB
- 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.