Let's say I have a collection of comments. Every comment object has a "doc ref" to the user who posted. I need a query that will return a list of comments including the value of every single user reference, so my query returns a nice formatted of Json comment objects.
相关问题
- adding sha1 in firebase app fails with error
- firebase storage cors strange Behaviour
- Firebase security rules difference between get() a
- Firebase security rules difference between get() a
- LoginActivty with Firebase & Facebook authenticati
相关文章
- How can make folder with Firebase Cloud Functions
- Firestore Update a document field Using Rest API
- How to convert a FCM token to APNS token?
- App not showing Notification receiving FCM when th
- Android Studio - Get Firebase token from GetIdToke
- How to combine Firestore orderBy desc with startAf
- Remove Duplicates from an Array of GeoFire Objects
- Is it possible to test a Firebase trigger locally?
A similar question was asked here What is firestore Reference data type good for?, I don't think it is possible to do what you are asking according to this answer https://stackoverflow.com/a/46570119/473453.
You have to load every reference yourself, e.g.
For many comments this will add a lot of overhead. Maybe you can write a CloudFunction that does the work for you all on the server side and returns you a formatted JSON.
It looks like they might e working on supporting this in the future though: https://stackoverflow.com/a/46614683/473453
I create a solution for this, at least work for me!
Imagine u have 2 collections: users and friends and Users has one document: User1 and Friends has one document too: Friend1.
So User1 has a reference field with this text: Friends/Friend1.
U can get all Users and for each one u can build a map like this:
I suggest you duplicate the user data in each comment. Create a field in the comment doc that is an object named
user
and provide the minimum amount of information required to display the comment. So yourcomment
doc might look like...Now, you have everything you need to display the comment. If someone clicks the author of the comment, you can then take the id and use it to load the full profile of the commentor.
Data duplication is frowned upon in relational databases since they are built to handle these scenarios with foreign keys.
However, in NoSQL databases like firestore, data duplication is actually encouraged to simplify queries as well as reduce the amount of data sent over the network.
If you had loaded the full
user
document for each comment, you'd likely be loading much more information about the user than is required to display the comment.This annoyed the hell out of me as well. I made a utility helper, that can automatically populate the first level.
Helper
Example usage:
Limitation: This example will not work for deep nested references
Adding to ChrisRich response. If the desired field is an array of references you can use the following code: