How do you connect the backend to the frontend in REACT?

ERROR in ./src/App.js 5:0-38
Module not found: Error: You attempted to import …/backend/Models/PartSchema which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project’s node_modules/.
@ ./src/index.js 7:0-24 11:33-36

^^ Above Error…

So I got my backend connected to MongoDB and running, and I think I got the proper schema for my collection in MongoDB…

Now I am trying to map() through my collection (collection named “part” in MongoDB) and throw the result on a table on my frontend in App.js

… But I am getting the error shown above…

How do I properly fetch the schema from the backend folder to map it on the frontend?

The code I have is this:

in the server.js in my backend folder:

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");

require("dotenv").config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true });

const connection = mongoose.connection;
connection.once("open", () => {
  console.log("MongoDB database connection established successfully");
});

app.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});

In my Backend folder / Models folder I got:
I think this will connect me to the “part” collection in the MongoDB connection that is working good from the proper database.

import mongoose from "mongoose";
const { schema } = mongoose;

const partSchema = new schema({
  Reference: String,
  Description: String,
  Replacements: String,
});

const part = mongoose.model("part", partSchema);

module.exports = part;

Now I want to catch the information and print it on my frontend in App.js under the src folder… trying to do something like this which is not working.

import "./App.css";
import "../backend/Models/PartSchema";

function App() {
  return (
    <div className="App">
      <h1>Here is a table </h1>
      <table>
        <thead>
          <tr>
            <th>Reference </th>
            <th> Description </th>
            <th>Replacements </th>
          </tr>
        </thead>
        <tbody>
          {Part.map((item) => (
            <tr>
              <td>{item.reference}</td>
              <td>{item.description}</td>
              <td>{item.replacements}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default App;
1 Like

I believe it should be with a smaller “p” for {part.map((items… still doesn’t work…

It looks like your roughly trying to load/run Mongoose in React.

This wont work. Mongoose is designed to run in nodejs (server-side), and work with your server-side code to connect to MongoDb.

However, React normally is used to create UIs in the browser (client-side). You can’t directly use the two together. The primary reason for this is where React runs is usually the browser, where-as nodejs is the back-end, and thus its own runtime. **Thus the two processes that make up the full stack are running not only in different contexts (browser, nodejs) but also probably different computers!

Another consideration is the JS you write for React is usually jsx, which is JavaScript, except with extra syntax to essentially write HTML/CSS in the same file. Nodejs can’t directly run this format (nor can browsers!), and React comes with tools to compile this jsx to JS that can then be used on the client-side.

Furthermore nodejs provides a different runtime, and thus APIs to the code you write. For example, you can change the filesystem in nodejs, but you can’t do such in the browser (otherwise websites could delete your entire hard drive!).

So again, it might be JavaScript, but where that JavaScript can run, and what it can “do” is different depending on the context.

You’ll need to use something like express to create endpoints that your React can call to get data from Mongoose, and then return it to the client-side via http calls, usually using something like fetch.

Its also worth mentioning that there is a way to use React to render page’s on the server-side, that then get “sent” to end-user’s after React is compiled. However, I don’t recommend doing this right now, as its less common.

uff…

Apparently I need a different approach if I want to use REACT for this. I would like to stick to the MERN platform if possible.

I have installed Mongoose, Express, Cors, dotenv and nodemon, all of them are installed under the /backend folder and I got the server connected and running.

I understand you can do some CRUD operations with this setup? Not sure, but either way, this is not really a CRUD operation.

The end point of this operation would be to get the data from MongoDB, map it, print it, add global filter, and pagination…

I’ll be investigating a bit more on the fetch method to see how to integrate it…

Thanks…

The MERN stack is fine for this, with the original setup your essentially skipping the E, or express part. Or at least that is what it appears your doing. The Express part will manage your actual web-server and act as the “middleman” between your React front-end and the database.

This is a CRUD operation, where you are doing a Read (the R) of the list of parts in the database within your React app.

Assuming you already have data in your database, and your schema is defined with that data, you’d have to do the following main steps to get the data to appear in React:

  1. Setup an express GET route that will return the list of parts from the database.
    a. You can “skip” React entirely by going to the URL your running your back-end server on via the browser, so for example: localhost:8080/parts would show you the list of parts as returned by the database, and passed along via express.

  2. Update React to get data asynchronously from your back-end. Here’s docs on this: https://reactjs.org/docs/faq-ajax.html
    a. Its worth noting that “getting the data” is actually somewhat complicated in JS, and web development in general. What makes it deceiving is the fact everything is done asynchronously. What I mean by this is React should show something while the data is being returned from the back-end. It could be a loading spinner, or something else, but it must “do something” while the data is being returned. This also means the data can be returned at some obscure point in the future. If your internet is fast it might be only milliseconds, but in the real world latency can be noticeable. However, the key thing is you’ll use fetch to get the data, and React has patterns to manage how to update what you see once it comes back.

This is where things can get complicated, and confusing. Its one thing to call 1 endpoint to get data, its another to dynamically pass along “filters” from the front-end, to the back-end, then translate them to filtering within the database. This is called server-side pagination. Its really the only option if you have a lot of data in the database.

I wont get into how to deal with server-side pagination, just know it can get complicated and requires juggling more complex state beyond just “get me parts”.

1 Like

I got Express installed on the /backend folder for the server.js … the first set of code is actually for the server.js to connect to MongoDB… I got successfully connected to MongoDB, then I created Schemas in a different folder.

Now, moving to the frontend, under the src folder… are you saying I need to use some Express code in the App.js where I want to print the database?

Now, I do have some sample code for pagination and global filtering, not sure if they are pulling data from database or not… the other option is to investigate the MongoDB Atlas documents and I understand you can do that from the server side as well.

For now I am working on printing the database on the frontend … I am trying to import the schemas to then map it, but I am getting an import error because they are outside the src folder.

Thanks much for all your information…

Yes, at this current time I’d actually not try to use React what-so-ever.

If your “in React”, your bypassing where express, and your back-end server-side code should go. Again, you can’t use React with data from the database until your express, and thus your server-side code is finalized.

Another way you can focus on just the express part is focusing on express by itself:

From there, you can add your mongoose code, and use it to return data from your database rather than returning “hello world”. You could also create another project with bare bones express just to focus on that part of the stack, rather than trying to jump through all of it together without a firm understand how each work on their own, or why they are split up in the first place.

Again, your imports from your mongoose schemas wont work in React.

I highly recommend not trying to use any snippets until you have a firmer understanding of which parts are doing what within the stack.
Using snippets that “magically work” could introduce more issues rather than help. Its one thing to have a clean slate and not sure where to go/start, its another to have a pile of “snippets” and not sure what’s wrong. Its similar to searching for a needle in a haystack… except you don’t even know what the needle looks like!
There’s usually a few ways to do things correctly with slight fluctuations, but there are infinite ways to screw things up.

Ok cool… I could print the table using Express… I guess… do all of the work required for that table in Express and put the code in my /backend folder…

At what point do I transfer this information to the frontend?

Obviously I might need to take a pause and learn more about the entire system and how it connects…

I was following one of the FreeCodeCamp YouTube videos on MERN… I don’t want to do exactly that they are doing, but something similar.

Maybe? I can create the routes and pages on the backend with the table /s I want… then link the page…

This is where is a bit blurry… how/when to transfer all the backend work to be shown on the front end…

I’ll be doing another re-re-refreshment … the course I took on REACT (from Udemy, not FreeCodeCamp) didn’t cover much of backend work, so I kind of know how to code some stuff, but not really how to connect them together…

I recommend focusing primarily on using express by itself, and understanding how it fits into the stack.

You could use express to send compiled HTML/CSS to the end user’s browser. This would be where you essentially create the final product the user’s browser will see, and send it over.

However, the limitation of such approaches is if the user wants to view/do-something, then the entire page will have to be sent back over again from the server. This usually leads to a slower user experience as it takes noticeable moments to “do anything” as the whole page needs to be updated and sent over from the back-end.

This entire approach is the traditional way websites were done and handled 20 years ago, and is called server-side rendering. This is back when computing power was less, and having most of the work done on servers was the only way to go.

You could also work on freeCodeCamp’s curriculum to learn these topics via challenges, and projects. This is the section that focuses on the back-end:

I think you’re missing the “connection” part of using React, and how express fits in the whole thing.

As such, I’d focus on making sure you have a good grasp of using express by itself, then maybe mix in mongoose+mongodb (or some other database) and only once your able to handle “server-side” then look back into leveraging React and connecting to your back-end.

Good luck, keep learning keep growing :+1:

Yep… I got some Express courses too. I need to review them to understand how it helps with the MERN integration.

What do you think is the best way to go about it? I am in no hurry and this is a learning project.

Eventually I want to create a few MongoDB Collections, and send them to the front end with the options of filtering and pagination.

To work with MongoDB Atlas they have the options of working with Noje.js (I believe this is what I am trying to do), using Realm, or doing an API… What do you think makes more sense for this application?

Thank you much for all your information…

So just for clarity, MongoDB is the name of the database software/server you’d connect to. MongoDB is also the name of the company that created that software. MongoDB Atlas is the name of the service(s) MongoDB the company provides to interact with their database.

Currently you want to use mongodb with nodejs. The other offerings could help you maintain/use MongoDB, and MongoDB Atlas’s features to do more fancier things, but you just need the bare-bones-basic MongoDB database to handle your data.

1 Like