Query data in multiple collections

不羁的心 提交于 2020-07-31 04:36:08

问题


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:

Please help


回答1:


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.




回答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.




回答3:


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



来源:https://stackoverflow.com/questions/53474876/query-data-in-multiple-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!