admin管理员组

文章数量:1290520

I was wondering if there's a way to insert documents into a MongoDB collection directly from a React ponent.

My current personal project (for training purpose) is a little chat web application. So for example, when my user wants to post a new message in a room, the input ponent should look something like this:

var NewMessageInput = React.createClass({
  postMessage: function(value) {
    db.collection.insert({
      content: value
    });
  },
  render: function() {
    return (
      <div>
        <input onSubmit={() => this.postMessage(value)}>Type your message here</input>
      </div>
    );
  }
});

I know how to get an app running with Express, React, and MongoDB but I'm only able to insert document with the mongo shell and querying them at the route loading. Plus, I would like to use only react-router for my routes and that's why I have this question.

I was wondering if there's a way to insert documents into a MongoDB collection directly from a React ponent.

My current personal project (for training purpose) is a little chat web application. So for example, when my user wants to post a new message in a room, the input ponent should look something like this:

var NewMessageInput = React.createClass({
  postMessage: function(value) {
    db.collection.insert({
      content: value
    });
  },
  render: function() {
    return (
      <div>
        <input onSubmit={() => this.postMessage(value)}>Type your message here</input>
      </div>
    );
  }
});

I know how to get an app running with Express, React, and MongoDB but I'm only able to insert document with the mongo shell and querying them at the route loading. Plus, I would like to use only react-router for my routes and that's why I have this question.

Share Improve this question edited Mar 20, 2017 at 2:48 Emile Bergeron 17.4k5 gold badges85 silver badges131 bronze badges asked Mar 19, 2017 at 17:54 KuroAkuKuroAku 2351 gold badge3 silver badges7 bronze badges 1
  • Check this npmjs./package/mongodb and note that that's the server-side. – elmeister Commented Mar 19, 2017 at 18:38
Add a ment  | 

2 Answers 2

Reset to default 4

I'm guessing you'll need the database on the server, so you may need an API to post the data since the database itself isn't on the client. I use Superagent for sending the data and Mongoose to create a schema and mongo database.

messageModel.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

// create a schema
const messageSchema = new Schema({
  // You may need to add other fields like owner
  addedOn: String,
  message: String,
});
const Message = mongoose.model('Message', messageSchema);
module.exports = Message;

server.js

import Message from './models/messageModel';

mongoose.connect('mongodb://user:pass@localhost:port/database');

app.post('/api/messages', (req, res) => {
  const doc = new Message({ message: req.body.message })
  doc.save();
});

client.js

import React, { Component } from 'react';
import request from 'superagent';

class ponentName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      message: '',
    };
    this.handleMessageInput = this.handleMessageInput.bind(this);
  }
  handleMessageInput(e) {
    this.setState({ message: e.target.value });
  }
  handleSubmitMessage() {
    console.log('starting to submit profile');
    if (this.state.isFormFilledProfile) {
      console.log('Profile Form appears filled');
      const data = {
        message: this.state.message,
      };

      request
        .post('/api/messages')
        .send(data)
        .set('Accept', 'application/json')
        .end((err, res) => {
          if (err || !res.ok) {
            console.log('Oh no! err');
          } else {
            console.log('Success');
          }
        });
    }
  }
  render() {
    return (
      <div>
        <div>
          <form onSubmit={this.handleSubmitMessage}>
            <input
              onChange={this.handleMessageInput}
              value={this.state.message}
            />
            <button type='Submit' value='Submit'>Submit</button>
          </form>
        </div>
      </div>
    );
  }
}

export default ponentName;

You may need to also go through the react forms guide here. All the best!!!

Ok so because React is a front end framework you will not have access to things on your backend such as methods like db.collection.insert(). You will in tern has a separation of front end code and back end code. They will talk to each other through HTTP requests (GET, POST, PUT, DELETE).

Side note just to clarify. You will still need express for routing as well as react-router. They do different types of "routing". Express will handle routing of mainly your API, all the data calls that your front end will make to it. React-router handles page changes on your front end, right within the bowser. This keeps your page from reloading each time the user moves around.

So lets get into a little code.

On your back end you will need an express endpoint for your app to talk to. In this example I will show use with the package mongoose as it is a tool that is monly used with a node.js backend.

https://www.npmjs./package/mongoose

var mongoose = require('mongoose');
var Message = require('../models/message');

app.post('/message', (req, res) => {
  var newMessage = new Message(req.body);
  newMessage.save((err, doc) => {
    if (err) {
      res.send(err);
    } else {
      res.send(doc);
    }
  });
});

This code will handle a post request at the url "/message". It will proceed to create a new message from the data in the request (req) body. Then save that to the database. After the save is successful it will send back the document that was just saved.

In mongoose we create a schema for each of our data models like such:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var MessageSchema = new Schema({
  content: {
    type: String,
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

var Message = mongoose.model('Message', MessageSchema);

module.exports = Message;

Now on the front end / React side of things we need to send our message data to the backend to save. We can use a package like axios to make clean promise based HTTP requests from the browser.

https://www.npmjs./package/axios

var NewMessageInput = React.createClass({
  postMessage: function(value) {
    axios.post('/message', {
      content: value
    })
    .then(function (message) {
      console.log(message);
    })
  },
  render: function() {
    return (
      <div>
        <input onSubmit={() => this.postMessage(value)}>Type your message here</input>
      </div>
    );
  }
});

And that should do it!

For a backend example check out this repo I have setup. It's very basic but will be a good example of a backend with mongoose for reference.

https://github./Alexg2195/simple-dev-example

Also here is a bit of some side content I created for teaching React that may be a good reference.

https://github./Alexg2195/UT-ReactJS

本文标签: javascriptInsert MongoDB document with ReactjsStack Overflow