Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modelling a Chat like Application in Firebase

I have a Firebase database structuring question. My scenario is close to a chat application. Here are the specifics

- users(node storing several users of the app)
  - id1
      name: John
  - id2
      name: Meg
  - id2
      name: Kelly
- messages(node storing messages between two users)
  - message1
      from: id1
      to: id2
      text: ''
  - message2
      from: id3
      to: id1
      text: ''

Now imagine building a conversations view for an individual user. So I want to fetch all messages from that particular user and to that particular user

I am writing it as follows right now:

let fromMessagesRef = firebase.database().ref('messages').orderByChild('from').equalTo(firebase.auth().currentUser.uid)
fromMessagesRef.once("value").then((snapshot) => {/* do something here*/})

let toMessagesRef = firebase.database().ref('messages').orderByChild('to').equalTo(firebase.auth().currentUser.uid)
toMessagesRef.once("value").then((snapshot) => {/* do something here*/})

Questions:

  1. Is this the right way to model the problem?
  2. If yes, is there a way to combine the above 2 queries?
like image 753
Rajat Avatar asked Sep 01 '16 02:09

Rajat


People also ask

Can Firebase be used for chat?

Welcome to the Friendly Chat codelab. In this codelab, you'll learn how to use the Firebase platform to create a chat app on Android.

How do I create a chat in Firebase?

1. Create an Android Studio Project. Fire up Android Studio and create a new project with an empty activity called MainActivity for the Firebase chat app example. To configure the project to use the Firebase platform, open the Firebase Assistant window by clicking on Tools > Firebase.


1 Answers

I would store the data like this:

- users(node storing several users of the app)
  - id1
      name: John
      messages
        message1: true
        message2: true
  - id2
      name: Meg
      messages
        message1: true
        message3: true
  - id3
      name: Kelly
      messages
        message2: true
        message3:true
- messages(node storing messages between two users)
  - message1
      from: id1
      to: id2
      text: ''
  - message2
      from: id3
      to: id1
      text: ''
  - message3
      from: id2
      to: id3
      text: ''

Firebase recommends storing things like this. So in your case your query would be

let fromMessagesRef = firebase.database().child('users').child(firebase.auth().currentUser.uid).child('messages')

This allows it to be very fast as there is no orderBy being done. Then you would loop over each message and get it's profile from the messages node.

like image 71
Mathew Berg Avatar answered Oct 06 '22 00:10

Mathew Berg