0

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}`));

3
  • It would be hard to say exactly how to serve your data without seeing any code, but you will need to make API endpoints in express, and then call the endpoints from your React application using Axios (or Fetch API). You may need to proxy your server in the Webpack config, depending on how you have set your project up. Commented Apr 9, 2021 at 14:27
  • I have updated my code and in the code at the end of the url, I have my database_name. So, according to you If I simply pass my database name to frontend using axios then Can I iterate over the collections of database_name? Commented Apr 9, 2021 at 14:40
  • The way to do this would be to access the MongoDB database from the frontend using your express API and then just return data to your frontend. It is actually very similar to what you have in the GET route 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. Commented Apr 9, 2021 at 15:30

2 Answers 2

1

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 } })
    });
})
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your first contribution. Can you please correct the spelling of "moongose" :) That would improve your great answer and allows direct searching for it. Thanks mate!
Fixed. Thanks Bjorn for pointing that out. :D
ya, it is giving correct output on console but giving 404 not found error when applying to get a request from the frontend. Can you give some suggestions on what to apply instead of console.log(collection) so that it sends JSON format data to output?
Have you tried putting the array data into json response? const dataArr = []; collection.forEach(el => dataArr.push(el.name)); res.status(200).json({ status: 'success', data: { dataArr } })
Also, remove the next(); because res.json already ended the event loop.
|
0

{ "name": "Avengers: Endgame", "time": ["14:15", "16:00", "21:30", "23:00"], "rating": 8.8 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.