Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

javascript - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...