如何在客户端显示来自mongodb的数据?

时间:2018-10-27 11:28:56

标签: node.js reactjs mongodb

我已经使用nodejs / express,mongodb,reactjs创建了一个聊天应用程序。当我在聊天框中键入内容并单击“发送”按钮时,数据将存储在mongodb中,但是如何在客户端显示它。在下面的代码中,我无法在客户端显示它。在server.js中,我无法发出消息。我在server.js中做错了什么?数据没有从后端/数据库到达前端。

代码:

server.js:

const express = require('express');
const mongoose = require('mongoose');
const socket = require('socket.io');
const message = require('./model/message')

const app = express();

const mongoURI = require('./config/keys').mongoURI;

mongoose.connect(mongoURI, {useNewUrlParser: true})
  .then()
  .catch( err => console.log(err));

let db = mongoose.connection;

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('disconnect', function(){
    console.log('User Disconnected');
  });

  let chat = db.collection('chat');

      socket.on('SEND_MESSAGE', function(data){
        let message = data.message;
        let date = data.date;

        // Check for name and message
        if(message !== '' || date !== ''){
            // Insert message
            chat.insert({message: message, date:date}, function(){
                socket.emit('output', [data]);
            });
        }
    });

    //Code below this is not working:
    chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
      if(err){
          throw err;
      }
      // Emit the messages
      socket.emit('RECEIVE_MESSAGE', res);
    });

})  

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.emit('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>
        )
    }
}

mongo shell的屏幕截图:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

猫鼬文档指定.find()方法的正确用法。您可以找到它here

要缩短进度,您需要为该方法提供您要寻找的对象模型。因此,例如,如果您要查找具有特定日期字段的对象,则可以使用:

chat.find({ "date": <some-date> }, function(err, objects) { ... });

如果要从集合中获取所有对象,可以使用:

chat.find({}, function(err, objects) { ... });