oolongloop
oolongloop

Reputation: 135

How do I connect mongoose/mongodb to my React App.js file

Most of the tutorials I am seeing use a express.js file to route all get and post requests. I am using a React component using react-router-dom, do I need to use express? If yes, what is the best way to do so? Here is what my app is looking like following along 1/4 of this tutorial so far: https://www.youtube.com/watch?v=WDrU305J1yw&t=1693s

The mongoose code is probably misplaced and breaks the app.

import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import mongoose from 'mongoose';

import '../styles/App.css';

import Input from './Input';

mongoose.connect(
  'mongodb://admin-01:[email protected]:27017,node-shot-log-shard-00-01-ecvwz.mongodb.net:27017,node-shot-log-shard-00-02-ecvwz.mongodb.net:27017/test?ssl=true&replicaSet=node-shot-log-shard-0&authSource=admin&retryWrites=true',
  {
    useMongoClient: true
  }
);

class App extends Component {
  render() {
    return (
      <div>
        <div>
          <Route exact path='/' component={ Input } />
        </div>
      </div>
    );
  }
}

export default App;

Upvotes: 1

Views: 2681

Answers (1)

nikos fotiadis
nikos fotiadis

Reputation: 1085

The best and correct way to do this is to have a backend server in whatever language you prefer(javascript, java, etc.) and connect this server with your database. Then in your react application when you need data from your database you will make a request to the server and the server will retrieve the data and them back to your react application.

Upvotes: 3

Related Questions