[英]How can I store data in mongodb using nodejs / express?
I have created chat application using socket.io and I am storing array of messages. 我已经使用socket.io创建了聊天应用程序,并且正在存储消息数组。 Each array object has
message
and date
. 每个数组对象都有
message
和date
。 The chat app is working only on client side ie when I refresh the page all previous chats are gone. 聊天应用程序仅在客户端运行,即当我刷新页面时,以前的所有聊天记录都消失了。 How can I store the messages programmatically ?
如何以编程方式存储消息? using mongodb, nodejs/express and reactjs on client side ?
在客户端使用mongodb,nodejs / express和reactjs?
Code: 码:
server.js: server.js:
const express = require('express');
const mongoose = require('mongoose');
const socket = require('socket.io');
const app = express();
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useNewUrlParser: true})
.then(() => console.log('Mongodb connected...'))
.catch( err => console.log(err));
const port = 5000;
let server = app.listen(5000, function(){
console.log('server is running on port 5000')
});
let io = socket(server);
io.on("connection", function(socket){
console.log("Socket Connection Established with ID :"+ socket.id)
socket.on('SEND_MESSAGE', data => {
io.emit('RECEIVE_MESSAGE', data);
});
})
messageSchema.js: messageSchema.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const MessageSchema = new Schema({
message: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Message = mongoose.model('Message', MessageSchema);
chat.js: chat.js:
import React, { Component } from 'react'
import './chat.css'
import io from "socket.io-client";
export default class Chat extends Component {
constructor(props){
super(props);
this.state = {
message: '',
date: '',
messages: []
};
const socket = io('localhost:5000');
this.sendMessage = event => {
event.preventDefault();
if(this.state.message !== ''){
socket.emit('SEND_MESSAGE', {
message: this.state.message,
date: Date.now()
});
this.setState({ message: '', date: '' });
}
};
socket.on('RECEIVE_MESSAGE', data => {
addMessage(data);
});
const addMessage = data => {
console.log(data);
this.setState({
messages: [...this.state.messages, data],
});
console.log(this.state.message);
console.log(this.state.messages);
};
}
render() {
return (
<div>
<div id="status"></div>
<div id="chat">
<div className="card">
<div id="messages" className="card-block">
{this.state.messages.map((message, index) => {
return (
<div key={index} className="msgBox"><p className="msgText">{message.message}</p></div>
)
})}
</div>
</div>
<div className="row">
<div className="column">
<input id="inputmsg" type="text" placeholder="Enter Message...."
value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
</div>
<div className="column2">
<button id="send" className="button" onClick={this.sendMessage}>Send</button>
</div>
</div>
</div>
</div>
)
}
}
Screenshot: 屏幕截图:
What modifications should I make in server.js and chat.js so that the chat messages get stored in mongodb database. 我应该在server.js和chat.js中进行哪些修改,以便将聊天消息存储在mongodb数据库中。 Do I need to create API endpoint for storing and retrieving previous chats ?
我是否需要创建API端点来存储和检索以前的聊天记录? Note: I have setup mongodb in mlab with database name
mongochat
and collection name = chat
. 注意:我已经在mlab中用数据库名称
mongochat
和集合名称= chat
设置了mongodb。
You can try edit your server.js, and do something like this: 您可以尝试编辑server.js,然后执行以下操作:
var messageSchema = require("path/to/schema");
.
.
.
socket.on('SEND_MESSAGE', data => {
io.emit('RECEIVE_MESSAGE', data);
var newDate = new Date();
const message = new messageSchema({
'message': data,
'date': newDate
})
message.save((err, data) => {
if(err) //do something
else // do whatever you want
})
});
You can also create a middleware to provide you a simple service between the MongoDB and the APP. 您还可以创建中间件,以在MongoDB和APP之间为您提供简单的服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.