简体   繁体   中英

How to get data from mongodb on client side?

I am not able to display data on client side. The data is getting stored in mongodb collection but I am not able to send the data on client side. I want to send conversation data between two users on client side but I am getting empty array in console why so ? Is .find() wrong in server.js file ? I have added server.js and chat.js (client file where I want to display the data)

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);
    })


  }) 

chat.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 });
    }

Sample data which gets stored in database:

{
    "_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
        }
    ]
}

screenshot:

在此处输入图片说明

Hmm, you call conversation.find({ user1: user1 }) in "the same" time with connection event, then user1 is undefined now. You can put console.log(user1) in above the query to check user1 value:

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

Output log => Before find user query: undefined , this is reason data what you send to client is a empty array.

Hotfix: Just query and send data to client when you really get 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);
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM