I have my backend ready with express and MongoDB. MongoDB contains various collections.
I want to access the MongoDB database to react.js frontend and iterate over the MongoDB database so that I can show(print) the collection's name on the UI. How can I do this?
This is backend code
import express from "express";
import mongoose from "mongoose";
import Messages from "./messages.js";
import cors from "cors";
// app configuration
const app = express();
const port = process.env.PORT || 9000;
//middleware
app.use(express.json());
app.use(cors());
// DB Configuration
const url = "mongodb+srv://suraj_bisht_99:[email protected]/database_name";
mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('mongoDB is connected'))
.then(err => console.log(err));
// API routes
app.get("/", (req, res) => {
res.status(200).send("Hello World");
})
app.get("/messages/sync", async (req, res) => {
await Messages.find( (err, data) => {
if(err){
console.log(err);
res.status(500).send(err);
}else{
res.status(200).send(data);
}
})
})
app.post("/messages/new", async (req, res) => {
try{
const newMessage = new Messages(req.body);
const newMessageCreated = await newMessage.save();
res.status(201).send(newMessageCreated);
}
catch(err){
res.status(400).send(err);
}
});
// listening part
app.listen(port, () => console.log(`listening on port number ${port}`));
GETroute for/messages/sync. Just set up a route for what you want in express then from your frontend send a GET request to this route which returns the data you need. You should not access the database directly from your frontend, do not pass any database urls, passwords, usernames to the frontend leave it all to backend.