Arrays or subcollections in Firebase Firestore?

Viewed 23

I have created a Firebase database with the following structure: There are 3 main collections: Users, Chats and another one which is not important for now. I have initially planned to store type documents in the Users collection, the type User is made of the properties:

uid         -> string
... (some others which are not important)
displayName -> string
chatsList   -> a SUBCOLLECTION of chat references, containing
    chat ID
    otherUserID -> the ID of the other user chatting with you
    
contacts  -> a SUBCOLLECTION of user references, containing
    user ID
    user displayName

type Chat is made like this (note that the chat is only between two users):

uid      -> string
user1    -> ID of one of the users in this chat
user2    -> ID of the other user
messages -> a SUBCOLLECTION of messages made of:
    uid       -> message ID
    senderID  -> user ID of who sent the message
    text      -> content of the message
    timestamp -> when was this message sent
    

So if I am a logged in user I know my id and if I want my chat with user id 123 I can query the collection "users/:myID/chatsList" and find the chat reference which satisfies: "otherUserID", "==", "123" Then pick the related chat ID and find the actual chat in the Chats collection.

I am not sure but I understand that queries are shallow, so if I query for example the Chats collection I am not considering the subcollection Messages at all, so it should be faster?

Now the question is: do you think this is a good structure or is it better to not have those subcollections and use something like an array instead?

1 Answers

If I query for example the Chats collection I am not considering the subcollection Messages at all, so it should be faster?

Firestore queries are fast irrespective of you are fetching a document from a collection of 10 documents or 10 thousand. The only thing that can make your query slow is querying many documents at once as you will be downloading a lot of data.

Is it better to not have those subcollections and use something like an array instead?

This totally depends on your use case. Firestore documents have a max size limit of 1 MB so if there is no limit on how many messages, it's better to use a sub-collection.

Using a sub-collection can make it easier to:

  1. Fetch/Update/Delete a single message by ID
  2. Paginate the messages (when fetching a document, you get all the data in it)

If you need either of the features above, it might be better to use a sub-collection.

Do checkout Firebase Realtime Database that sounds like a better option for chat applications in terms of pricing as well.

Also checkout: How to shard data Realtime Database for chat app?

Related