Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice Needed: How to properly connect React to MongoDB

I have been investing some time learning React, MongoDB, and other JS web app related tools. For a small project that I created, I am using this repository to create my toy app Create React App with no build. As I've progressed through my app I've learned a lot of React related tools and materials after the fact.

The part that I am stuck on is I am trying to submit a contact form's data into MongoDB but so far I'm unsuccessful in hooking up my app with MongoDB.

Here is my code for MongoDB. I've pretty much copy and pasted the code from the MongoDB guides onto my web app into a src/modules/mongo.js file

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const ObjectId = require('mongodb').ObjectID;
const url = 'mongodb://localhost:27017/danielrubio';

const insertFormData(db, callback) {
   db.collection('contactsubmissions').insertOne( {
      "name": name,
      "message": message,
      "email": email
    }, function(err, result) {
    assert.equal(err, null);
    console.log("Inserted a document into the restaurants collection.");
    callback();
  });
};

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  insertDocument(db, function() {
    db.close();
  });
})

The above code is straightforward, it basically inserts one document into a collection.

Here is my second file in src/modules/contact.js

import React, { Component } from 'react';
import Formsy from 'formsy-react';
import { FormsyText } from 'formsy-material-ui/lib';
import Paper from 'material-ui/Paper';
import RaisedButton from 'material-ui/RaisedButton';
import Snackbar from 'material-ui/Snackbar';
import '../assets/css/style.css';

class ContactForm extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = { open: false };
  }

  handleSubmit(data) {
    db.insertDocument({
       form submission info
       db.close()
    })
  }

  ......more code.....

  }

Now so far, I've been able to work through the MongoDB guides, I've created my database, can access the console, and can insert data through the console. What I haven't figured out is how to wire my app to mongodb so when I click a submit button it will insert the document in the right database. Coming from Rails and using a little bit of Flask, I can usually call a .create method which connects to my database or do some sort of SQL Alchemy operation which opens and closes the database. I've tried this approach by attempting to combine the two files together but when I do that, I can't even run npm start otherwise I get these types of errors:

Error in ./~/mongodb/lib/gridfs/grid_store.js
Module not found: Error: Cannot resolve module 'fs' in /Users/drubio/Desktop/react_personal_website/node_modules/mongodb/lib/gridfs
 @ ./~/mongodb/lib/gridfs/grid_store.js 42:7-20

Error in ./~/mongodb-core/lib/connection/connection.js
Module not found: Error: Cannot resolve module 'net' in /Users/drubio/Desktop/react_personal_website/node_modules/mongodb-core/lib/connection
 @ ./~/mongodb-core/lib/connection/connection.js 5:10-24

Error in ./~/mongodb-core/lib/connection/connection.js
Module not found: Error: Cannot resolve module 'tls' in /Users/drubio/Desktop/react_personal_website/node_modules/mongodb-core/lib/connection
 @ ./~/mongodb-core/lib/connection/connection.js 6:10-24

So my question is how can I simply connect my app to open the mongodb database and write to it? I've been reading a lot of tutorials but then I get rabbit holed and confused further talking about Express, Mongoose, Flux and on and on. From a high level overview it seems like I don't even need Express or Mongoose, I simply just want to insert my data without a schema and to be honest I don't really get what Flux is but from what I gather, I don't really need it for my small app (I think). I could use a little nudge in the right direction on this one. Thanks.

  [1]: https://github.com/facebookincubator/create-react-app
like image 308
Dan Rubio Avatar asked Nov 21 '16 16:11

Dan Rubio


People also ask

How do you connect to MongoDB using React?

First, we create a react app, and then for backend maintenance, we create API in node. js and express. js which is running at a different port and our react app running at a different port. for connecting React to the database (MongoDB) we integrate through API.

How do you use Node and React together?

export default App; Now run the Nodejs process npm run dev in one terminal and in another terminal start Reactjs using npm start simultaneously. Output: We see react output we see a button “Connect” we have to click it. Now when we see the console server-side we see that the ReactJS is connected with NodeJS.

What is MongoDB in React?

Mongo DB: A document-based open-source database, that provides you scalability and flexibility. Express JS: A structured base designed to develop web applications and APIs. React JS: A Javascript Front-end library for building user interfaces.


1 Answers

You have to create endpoint (server side) can be Node can be something else like php, and there you will accept request and insert the data to your database. Your React app will make ajax call to the server and the server will put the data to the database

If you want to do that with express you can create simple express app with one route that will get the data from the client and will send that to MongoDB. you dont have to use Mongoose you can use MongoDB driver or outer to simply send the data to MongoDB.

like image 120
Ariel Henryson Avatar answered Oct 20 '22 00:10

Ariel Henryson