【问题标题】:How to get data from mongodb on client side?如何在客户端从 mongodb 获取数据?
【发布时间】:2019-04-08 20:14:29
【问题描述】:

我无法在客户端显示数据。数据存储在 mongodb 集合中,但我无法在客户端发送数据。我想在客户端的两个用户之间发送对话数据,但我在控制台中得到空数组,为什么会这样? server.js 文件中的.find() 是否错误?我添加了 server.js 和 chat.js(我想要显示数据的客户端文件)

server.js:

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');
  let conversation = db.collection('conversation'); 
  let user1,user2;

      socket.on('GET_USER', function (data) {
        console.log(data);
         user2 = data.user2;
      });

      socket.on('LOGGEDIN_USER', function(data) {
        console.log(data);
         user1 = data.user1;
      });

      socket.on('SEND_MESSAGE', function(data){

        let author = data.author;
        let message = data.message;
        let date = data.date;

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

            conversation.findOne({ $and :[{user1: user1}, {user2: user2}] }, function (err, existingConversation){
                if(existingConversation === null){
                  conversation.insert({user1: user1, user2: user2, conversation: [{author: author, message: message, date:date}] })
                }else{
                  conversation.update({user1: user1, user2: user2}, 
                    {$push: {conversation : { author : author ,message : message,date : date }}  })
                }
            })

        }
      });

    conversation.find({ $and : [ {user1: user1}, {user2: user2} ] }).sort({_id: 1}).toArray(function (err, res) {
      if(err){
          throw err;
      }
          // Emit the messages
      io.emit('RECEIVE_MESSAGE', res);
    })


  }) 

聊天.js:

componentDidMount() {
      this.props.fetchUsers();
      this.socket.on('RECEIVE_MESSAGE', data => {
          console.log(data);         <--- This shows empty array in browser console
          this.addMessage(data);
      });
    }

    sendMessage(event) {
      event.preventDefault();

      if(this.state.message !== ''){
        this.socket.emit('SEND_MESSAGE', {
            author: this.props.match.params.user,
            message: this.state.message,
            date: Date.now()
        });

        this.socket.emit('LOGGEDIN_USER', { user1: this.props.match.params.user});
      }
    };

    addMessage(data) {

      this.props.saveAuthor(this.props.match.params.user)
      this.props.saveMessages(data)

      this.setState({
        message: ''
      });

    };

    handleClick = (userName) => {
        this.socket.emit('GET_USER', { user2: userName });
    }

存储在数据库中的示例数据:

{
    "_id": {
        "$oid": "5be039cf2b04ba5594939d48"
    },
    "user1": "Aditya",
    "user2": "vineet",
    "conversation": [
        {
            "author": "Aditya",
            "message": "Hello from Aditya",
            "date": 1541421517633
        },
        {
            "author": "Aditya",
            "message": "This is second message from Aditya",
            "date": 1541421556047
        }
    ]
}

截图:

【问题讨论】:

    标签: javascript node.js reactjs mongodb


    【解决方案1】:

    嗯,您在与connection 事件“同一”时间调用conversation.find({ user1: user1 }),那么user1 现在是undefined。您可以在查询上方输入console.log(user1) 以检查 user1 的值:

    console.log("Before find user query: ", user1)
    conversation.find({ user1: user1 })....
    

    输出日志 => Before find user query: undefined,这就是您发送给客户端的数据是空数组的原因。

    Hotfix:当你真正得到user1时,只需查询并向客户端发送数据

    socket.on('LOGGEDIN_USER', function (data) {
        console.log(data);
        user1 = data.user1;
    
        conversation.find({ user1: user1 }).sort({ _id: 1 }).toArray(function (err, res) {
            if (err) {
                throw err;
            }
            // Emit the messages
            io.emit('RECEIVE_MESSAGE', res);
        })
    });
    

    【讨论】:

    • 如果查询为conversation.find({ $and : [ {user1: user1}, {user2: user2} ] }).toArray(function (err, res) {,如何获取数据?我有更新的问题,请参阅
    • 您可以对LOGGEDIN_USER GET_USER 这两个事件进行查询,只需在查询前检查user1 &amp;&amp; user2即可。
    • 我无法在客户端显示数据?为什么这样 ?我没有在浏览器控制台中收到数据。
    猜你喜欢
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多