imdungnguyen
imdungnguyen

Reputation: 248

Query data in multiple collections

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

Upvotes: 9

Views: 24790

Answers (3)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

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.

Upvotes: 18

Lahiru Liyanage
Lahiru Liyanage

Reputation: 75

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.

Upvotes: 2

Mpwanyi Samuel
Mpwanyi Samuel

Reputation: 373

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

Upvotes: 1

Related Questions