Retrieving data from firebase for chat system

2019-08-07 09:38发布

问题:

Here is my firebase data -

I store a copy of every message under both the users -

I have 2 questions. -

Q1 - The query for extracting chat messages between user1 and user2 in an ordered fashion so it can be displayed in the personal chat window -

I wrote the following-

//refuser1 is firebase reference to "https://myapp.firebaseio.com/messages/user1"

var messages = [];        
refuser1.orderByChild("from").equalTo("user1").once('value', function(s){
s.forEach(function(childsnap){
messages.push(s.val());
});
});


refuser1.orderByChild("from").equalTo("user2").once('value', function(s){
 s.forEach(function(childsnap){
 messages.push(s.val());
 });
});
// Now messages array has all messages between user1 and user2 -
// add code to sort messages in array based on timestamp  /

Is this the correct way to store and retrieve data for personal one to one chat?

Q2 - When retrieving data , 'value' and 'child_added' events seem to act differently - See the image below - When i use 'value' i get all the child objects but when I use 'child_added' I get only the first child in users1 . The documentaion says that child_added is triggered for every initial child (assuming this means all the child that were existing before new child is added) Is my understanding correct? I was expecting the same returned result for 'value' and 'child_added'

回答1:

Q1) In NoSQL databases, you'll typically have to store the data in the way you want to use it. If you want to get the chat messages between specific users in a specific order, you should store them in that way.

chats
  user1_user2
    -K...c9
      from: "user1"
      message: "Hello message 1"
      time: ""
    -K...od
      from: "user1"
      message: "Hello message 2"
      time: ""
    -K...t8
      from: "user2"
      message: "Hello message 1"
      time: ""
    -K...c9
      from: "user1"
      message: "Hello message 1"
      time: ""
    -K...xb
      from: "user2"
      message: "Hello message 2"
      time: ""

In the above structure I've grouped the messages between user1 and user2 under a node user1_user2. This node serves as the "private chat room" between these two users: any time the same two users chat, their messages are added to this room.

Q2) You're doing once('child_added'. This means that you're telling Firebase to fire child_added only once and then to stop firing it. If you instead do on('child_added' it will be triggered for every initila child and all subsequent additions.