2

I am having some problems connecting to MongoDB database. After I launch my application using npm start it will not connect to the database.

Below the code that has the problem.

The error I am getting is on the return function below:

function App() {
  return (
    <>    / <-- Error here
    <Navbar /> 
    </>
  );
}

Below the App.js code:

import React from 'react';
import './App.css';
import './GoogleMap.css';
import './ProgressBar.css';
import Home from "./pages/Home";
import Vessels from "./pages/Vessels";
import SingleVessel from "./pages/SingleVessel";
import Error from "./pages/Error";
import GoogleMap from "./pages/GoogleMap";

import {Route, Switch} from "react-router-dom";
import Navbar from "./components/Navbar";

const app = express();
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require("body-parser");
const cors = require('cors');
const vesselsController = require("../controllers/VesselControllers");

require("../config/keys");

// DB Config
const db = require("../config/keys").MongoURI;

const options = {
    useNewUrlParser: true,
    reconnectTries: Number.MAX_VALUE,
    poolSize: 10
};

mongoose.connect(db, options)
.then(() => console.log('MongoDB Connection established'))
.catch((err) => console.log('Error connecting MongoDB database due to: ', err));

// Bodyparser
app.use(express.urlencoded({ extended: false }));

// Express Session
app.use(
    session({
        secret: 'secret',
        resave: true,
        saveUninitialized: true
    })
);

// Routes
const PORT = process.env.PORT || 3000; // my localhost port

app.use(bodyParser.urlencoded({extended: true, limit: '50mb'}));
app.use(bodyParser.json({limit: '50mb'}));
app.use(cors());
app.route("/vessels/all").get(vesselsController.getBaseAll);
app.route("vessels/:id/track").get(vesselsController.getCurrent);
app.route("/vessels").get(vesselsController.getHistory);
app.listen(PORT, console.log(`Server started on port ${PORT}`));

function App() {
  return (
    <>
    <Navbar /> 
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route exact path="/vessels" component={Vessels}/>
        <Route exact path="/vessels/:slug" component={SingleVessel}/>
        <Route exact path="/map" component={GoogleMap} />
        <Route component={Error} />
      </Switch>
    </>
  );
}

export default App;

What I have done so far:

1) I came across the following post but it was not totally useful to solve the error.

2) I can confirm that all necessary module have been installed and that is not an error of missing any dependency.

3) I also found this blog that helped in setting the connection but that still didn't work.

4) I can also confirm that I properly set the variables I am trying to store in the database according to the official documentation of MongoDB Schema

Thanks for pointing in the right direction for solving this problem

2
  • 1
    React is a client side framework, you won't have access to the server directly so you can't 'connect' to MongoDB with React that way. Commented Feb 7, 2020 at 14:09
  • See this boilerplate for an example on how to set it up properly: github.com/jefelewis/react-mongodb-rest-boilerplate Commented Feb 7, 2020 at 14:10

4 Answers 4

4

Looks like you are trying to execute a node application into a React application, this is not possible

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reading the question. So the javascript side should be a stand alone node? Like creating a different project and run it separately from a React application?
you need 2 separate applications, even if they both run javascript: one in React (aka frontend), one in node.js (aka backend). The frontend will use the backend API, the backend will operate over mongo.
4

React works on the client side where as Node and MongoDB work on the server side. What you need to do is build or use an API that lives on the server and communicates via HTTP/HTTPS messages to the client.

A React app can't do both, because it is sent to the client, the web browser, it has no way of connecting to a server outside of making request over the internet. That's why APIs are so helpful in web development. So you'll need an addition application to handle sending and receiving data via messages in HTTP.

Some resources to help you:

  • Here is a light weight tutorial for an easy introduction Medium Full Stack with Mongo and JS

  • Pluralsight's Full Stack JavaScript path and courses. They do a great job with content and will help explain a lot of concepts.

  • Alternatively LinkedIn Learning Learning has great resources as well.
  • YouTube which is a free option. Although with YouTube you may need to do more searching to find the right videos for your interest.

Comments

0

Hello you can use react in node as views with reactjs-express-generator

Comments

0

You need MongoDB Realm. There is a cool tutorial in MongoDB Website with Reactjs & GraphQL, etc...

good luck.

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.