9

I am developing a chat app using Firebase Firestore. I have a collection for room chat and another one for user info. How can I retrieve user data when I listen Room snapshot.

This is my database structure:

enter image description here

enter image description here

Please help

3 Answers 3

18

Firestore does not have the concept of server-side joins or projections across collections. Each query or document read can only take data from a single collection, or from all collections that have the same name with collection group queries. If you need to load data from two collections, you'll need at least two reads.

So in your case you'll need to load the user data separately, typically caching it in a collection in your code to prevent loading the same user too frequently.

Another alternative is to duplicate the data that you frequently need from each user into chat documents. This type of duplication is also quite common when modeling data in NoSQL databases.

For more on these topics, I highly recommend reading NoSQL data modeling and watching getting to know Cloud Firestore.

Sign up to request clarification or add additional context in comments.

Comments

2

You have to execute two separate reads. but the problem you will get is read data executes in the background you have to wait until the second read data is received.

Comments

1

You may not be able to query two collections at the same time but you can still get user details. I did the same thing when fetching post comments. What you need to do is have a UsersAdapter class that extends firestore recycler adapter class and do the same with the rooms collection. The firestore recycler adapter class listens to changes to data. So when you receive the data in the online method in the adapter class, u can get the rest of the data there before it's loaded to the recycler view.

I hope that makes sense

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.