Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Firestore: how to fetch a document reference inside my collection query and map it as a JSON value?

Tags:

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.

like image 458
Mauricio Silva Avatar asked Oct 22 '17 20:10

Mauricio Silva


People also ask

How do I find my collection reference on firestore?

CollectionReference collectionReference = FirebaseFirestore. getInstance(). collection("public_messages"); ArrayList<String> ids = new ArrayList<>(); //Contains your keys ArrayList<Task<QuerySnapshot>> tasks = new ArrayList<>(); for (String id : ids) { Task<QuerySnapshot> task = collectionReference.

What is subcollection in Firestore?

A subcollection is a collection associated with a specific document. Note: You can query across subcollections with the same collection ID by using Collection Group Queries.

How do references work in firestore?

< T > A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist. A DocumentReference can also be used to create a CollectionReference to a subcollection.


1 Answers

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.

const comments = [] firebase.firestore().collection('/comments').get().then(snapshot => {   snapshot.docs.forEach(doc => {     const comment = doc.data()     comment.userRef.get().then(snap => {       comment.user = snap.data()       comments.push(comment)     })   }) }) 

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

like image 193
user473453 Avatar answered Sep 26 '22 02:09

user473453