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.
- Check this npmjs./package/mongodb and note that that's the server-side. – elmeister Commented Mar 19, 2017 at 18:38
2 Answers
Reset to default 4I'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
版权声明:本文标题:javascript - Insert MongoDB document with React.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741500567a2382034.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论