Reputation: 39
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}`));
Upvotes: 0
Views: 1585
Reputation: 1
{ "name": "Avengers: Endgame", "time": ["14:15", "16:00", "21:30", "23:00"], "rating": 8.8 }
Upvotes: 0
Reputation: 34
In most case, don't do that. It can be a security risk.
Connecting directly to database from the front end can expose your database to attacks. You should create an API endpoints from your Express server that serve only the data you wanted for the frontend.
Here's an example using mongoose on express. This is just a console.log. You can iterate over your data from the server side and send only the names.
app.get('/collections', (req,res,next)=>{
mongoose.connection.db.listCollections().toArray().then(collection => {
console.log(collection)
});
next();
})
Here's my console output:
[
{
name: 'tours',
type: 'collection',
options: {},
info: { readOnly: false, uuid: [Binary] },
idIndex: { v: 2, key: [Object], name: '_id_' }
},
{
name: 'users',
type: 'collection',
options: {},
info: { readOnly: false, uuid: [Binary] },
idIndex: { v: 2, key: [Object], name: '_id_' }
}
]
EDIT: Here's the sample code with response with collection names as an array being sent to the frontend.
app.get('/collections', (req,res,next)=>{
mongoose.connection.db.listCollections().toArray().then(collection => {
const dataArr = [];
collection.forEach(el => dataArr.push(el.name));
res.status(200).json({ status: 'success', data: { dataArr } })
});
})
Upvotes: 1