使用 React.js 插入 MongoDB 文档 [英] Insert MongoDB document with React.js

查看:46
本文介绍了使用 React.js 插入 MongoDB 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法直接从 React 组件将文档插入到 MongoDB 集合中.

我目前的个人项目(用于培训目的)是一个小型聊天网络应用程序.因此,例如,当我的用户想要在房间中发布新消息时,输入组件应如下所示:

var NewMessageInput = React.createClass({postMessage:函数(值){db.collection.insert({内容:价值});},渲染:函数(){返回 (<div><input onSubmit={() =>this.postMessage(value)}>在此处输入您的消息</input>

);}});

我知道如何使用 Express、React 和 MongoDB 运行应用程序,但我只能使用 mongo shell 插入文档并在路由加载时查询它们.另外,我只想将 react-router 用于我的路线,这就是我有这个问题的原因.

解决方案

我猜你需要服务器上的数据库,所以你可能需要一个 API 来发布数据,因为数据库本身不在服务器上客户.我使用 Superagent 发送数据和 Mongoose 创建模式和 mongo 数据库.

messageModel.js

const mongoose = require('mongoose');const Schema = mongoose.Schema;//创建模式const messageSchema = 新架构({//您可能需要添加其他字段,如所有者添加:字符串,消息:字符串,});const Message = mongoose.model('Message', messageSchema);module.exports = 消息;

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';来自超级代理"的导入请求;类组件名称扩展组件{构造函数(道具){超级(道具);this.state = {信息: '',};this.handleMessageInput = this.handleMessageInput.bind(this);}处理消息输入(e){this.setState({ message: e.target.value });}处理提交消息(){console.log('开始提交个人资料');如果(this.state.isFormFilledProfile){console.log('个人资料表格显示已填写');常量数据 = {消息:this.state.message,};要求.post('/api/messages').发送(数据).set('接受', '应用程序/json').end((err, res) => {如果(错误 || !res.ok){console.log('哦不!错误');} 别的 {console.log('成功');}});}}使成为() {返回 (<div><div><form onSubmit={this.handleSubmitMessage}><输入onChange={this.handleMessageInput}值={this.state.message}/><button type='Submit' value='Submit'>Submit</button></表单>

);}}导出默认组件名称;

您可能还需要阅读 React 表单指南 在这里.一切顺利!!!

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

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 component 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'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 componentName 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 componentName;

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

这篇关于使用 React.js 插入 MongoDB 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆