2

I am having a very difficult time attempting to hook up my react application with a mongodb database. In a previous question that I asked regarding advice how to do it Connecting React with MongoDB, I received a push in the right direction. I have been attempting to follow along with this excellent tutorial on youtube MongoDB tutorial with Node and Express. However, there are some key differences that are making submitting form information very difficult. For example, here is a snippet of code from the youtube video:

index.html

<form action='/insert' method='post>
   <div> Input field one</div>
   <div> Input field two </div>
   ..........code.......
   <button type="submit">Insert</button>
</form>

And then in his routes/index.js he has this code:

var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient
var assert = require('assert')
var mongoUrl = 'mongodb::localhost...........'

router.post('/insert', function(req, res, next) {
  let formInput = {
     *form input hash with datan*
   }

   mongo.connect(url, function(err, db) {
    ........code to insert data into mongo......
   }
}

I can go deeper into the exact code if needed in the above example but I think it is very straightforward. Essentially this guy is connecting to the database with express and is capturing the data from his form and then inserting it into his database.

Here is my problem, the youtube video is not using React, furthermore it is not using what I am using which is Create-React-App Second, the form in the youtube video is using a form html element and my contact form is made completely with React and a tool called Formsy and Formsy material ui. A link to Formsy's properties shows that there is no action or method property Formsy handlers. So here is a snippet of my code below:

src/modules/mongo.js

const express = require('express');
const router = express.Router();
const mongodb = require('mongodb').MongoClient;
const assert = require('assert');
const mongoUrl = 'mongodb://localhost.......';

router.post('/insert', function(req, res, next) {
  let contactMessage = {
    name: req.body.name,
    email: req.body.email,
    message: req.body.message
  };

  mongodb.connect(url, function(err, db) {
    assert.equal(null, err);
    db.collection('message_submissions').insertOne(contactMessage, function(err, result) {
      assert.equal(null, err);
      console.log('message inserted');
      db.close();
  });
}

contact form in src/modules/contact.js

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

  handleSubmit(data) {
    console.log(data)

    ================PROBLEM==============
    How am I supposed to insert data to mongo db here?
    =====================================
  }

  ...........code.......

  render() {
    return(
      <div>
        <Paper className="Form" zDepth={2}>
          <Formsy.Form onSubmit={this.handleSubmit} action='/insert' method='post'
            <FormsyText
               required
               name="name"
               floatingLabelText="Enter your name"
            />

            .......more input.....
            .......more input.....

          </Formsy.Form>
        </Paper>
      </div>
    );
  }

How am I suppose to get my Formsy Form to insert to mongodb? When I try to export my router.post as a variable such as const mongo =router.post(....` I get very strange errors.

What makes matters worse are the number of tutorials that do not have a singular approach to this problem. For example here are a list of tutorials I have used to solve the client/server problem. None of these are the same and some of these involve fetching data from an API which is not what I want.

I just really wish there was a straightforward way of connecting to a db with React like the way Flask does. I've been struggling the most with this part. Is there some sort of glaring problem I'm taking with my approach. Better yet, if someone can point me to a repository that highlights a definitive example that would be very helpful.

Community
  • 1
  • 1
Dan Rubio
  • 4,709
  • 10
  • 49
  • 106
  • 1
    instead of using form method, use ajax, like `fetch` for instance, and send a POST request to your express route http://stackoverflow.com/questions/29775797/fetch-post-json-data – azium Nov 23 '16 at 20:08
  • Also making a comparison from React to Flask is entirely unfair because React is a client side application and Flask is a serverside application, hence why it has access to the db which is also on the server. The React code runs on *my* browser not *your* server – azium Nov 23 '16 at 20:10
  • please specify if you want to keep a design pattern – cajuuh Jun 28 '17 at 13:53

0 Answers0