0

is there any better way to get multiple specific data from collection in firestore? Let's say have this collection:

--Feeds (collection)
  --feedA (doc)
    --comments (collection)
      --commentA (doc)
        users_in_conversation: [abcdefg, hijklmn, ...] //Field contains list of all user in conversation

Then, I'll need to retrieve the user data (name and avatar) from the Users collection, currently, I did 1 query per user, but it will be slow when there are many people in conversation. What's the best way to retrieve specific users?

Thanks!

  • *it will be slow* - what is 'slow'? Are that 10,000,000 people in a conversation? What part is slow. Do you have some code you can share that is 'slow'? update the question with some details and we'll take a look. In the meantime please take a moment and review [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Jay Jan 29 '21 at 21:01

2 Answers2

1

Retrieving the additional names is actually a lot faster than most developers expect, as the requests can often be pipelined over a single HTTP/2 connection. But if you're noticing performance problems, edit your question to show the code you use, the data you have, and the performance you're getting.

A common way to reduce the need to load additional documents is by duplicating data. For example, if you store the name and avatar of the user in each comment document, you won't need to look up the user profile every time you read a comment.

If you come from a background in relational databases, this sort of data duplication may be very unexpected. But it's actually quite common in NoSQL databases.

You will of course then have to consider how to deal with updates to the user profile, for which I recommend reading: How to write denormalized data in Firebase While this is for Firebase's other database, the same concepts apply to Firebase. I also in general recommend watching Getting to know Cloud Firestore.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hi, thanks for your solution. Tried it and running well on the client-side, but very costly when renaming a user who has many messages. – Teguh Prabowo Jan 31 '21 at 07:04
0

I have tried some solution, but I think this solution is the best for the case:

  1. When a user posts a comment, write a field of array named discussions in the user document containing the feed/post id.
  2. When user load on a feed/post, get all user data which have its id in the user discussions (using array-contains)

it’s efficient and costs fewer transaction processes.