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

Mauricio Silva picture Mauricio Silva · Oct 22, 2017 · Viewed 43.4k times · Source

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.

Answer

user473453 picture user473453 · Oct 23, 2017

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