0

This is my database structure: enter image description here

I want new messages to generate a notification. How do i query this data to ensure the member is part of the conversation and then pass just the child_added of the new message.

This is what i have so far but it will return the entire conversation when a message is added.

const notificationChecker = database.ref("chats")
    .orderByChild(`members/${userId}`)
    .equalTo(true);

notificationChecker.on('child_changed', snapshot => {

  console.log(snapshot.val());

});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Jim
  • 570
  • 5
  • 15

1 Answers1

1

Since you're listening on chats, the result of your query will be child nodes chats. There is no way to change that behavior and it is one of the many reasons why experienced Firebasers recommend working with separate top-level lists for each entity type in your app.

It seems like you want the new messages for the current user in all conversations that they are part of. That is a three step process:

  1. Determine the current user
  2. Find what conversations they're part of.

    You'll typically do this by having a separate top-level list user-conversations, and then the UID as a key under that, and the conversation IDs as keys (with value true) under that. See https://stackoverflow.com/a/41528908/209103

  3. Find the new messages in each conversation.

    The best way to do this is to know what the last message is that the user saw in each conversation. In linear chat apps, you could model this by storing the key of the last chat message the user saw under /user-conversations/$uid/$conversationid, instead of the true we used above.

    If that is not possible, you can simply load the newest message for each conversation (conversationRef.orderByKey().limitToLast(1)) and then start listening from there (conversationRef.orderByKey().startAt(keyOfLatestMessage)).

    Either way, you will need to do this for each conversation that the user is part of.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807