Home > OS >  Firebase - Showing users that they have unread messages
Firebase - Showing users that they have unread messages

Time:11-04

I'm trying to determine the best way to handle showing the user that they have an unread message, in the navbar for example.

Currently I have separate documents for each conversation with data like so:

users: [ 'userId-1', 'userId-2' ]
messages: [
  {
    message: 'Test message',
    timestamp: 12345678910,
    userId: 123456
  },
  // etc...
]

Currently I'm thinking about adding an unread property to the message objects. Then, on page load, I would have to fetch each document where users contains the currentUser id and if any of the message objects in messages contains the unread: true property.

But then I would have to mark the message as read, but only for one of the users. So my data structure already doesn't work.

Also, this doesn't seem very performant to me, especially if the user has a great amount of conversations. Any idea on how to approach this differently?

CodePudding user response:

I'm trying to determine the best way to handle showing the user that they have an unread message, in the navbar for example

I understand that you only want to show a number of unread messages (or the information that there is a least one unread message). If this is the case you can get advantage of the new count() aggregation which takes into account any filters on the query.

Your data model is not 100% clear to me but since you have an Array of users, you could have an extra Array field containing the users that haven't read the message. So on page loading, you need to build the query of all messages where this array contains the currentUser uid and then call getCountFromServer() on this query.

Instead of being charged for each message that corresponds to the query you'll be charged one document read for each batch of up to 1000 index entries matched by the query.

  • Related