For chat organized into separate rooms or chat conversations, consider revising your structure to be the following:
/chat_messages/<room-id>/<message-id>/<message-data>
Using this structure, you can create a new room / conversation id by using a specific name of your choosing, or a Firebase-generated one using .push()
. Whenever you want to write a new message to this room, do the following:
var chatMessagesRef = new Firebase('<YOUR-FIREBASE>.firebaseio.com/chat_messages');
function sendMessage(roomId, message) {
chatMessagesRef.child(roomId).push(message);
}
Firebase essentially has two ways to query for data: by path and by priority (see Firebase Blog: Denormalizing Your Data is Normal for more information. Firebase push ids are automatically generated to sort chronologically, so you can fetch the n
most recent messages for any conversation using a limit()
query, such as:
chatMessagesRef.child(roomId).limit(20).on('child_added', function(snapshot) { ... });
Alternatively, you can fetch all messages for the conversation, automatically sorted chronologically, by removing the limit()
query in the above statement.
If you haven't already, check out Firechat, which is Firebase's official open-source chat client, and includes a fully-documented JavaScript client, data structure, and security rules for chat.