Skip to content
Advertisement

Firestore: get an array of objects

Is it possible to get an array of objects from Firestore. I tried something like below but I am getting undefined when I tried to log comments[0].comment

  let comments = [{}]
  try {
    const ref = firebase
      .firestore()
      .collection('comments')
      .where('ytid', '==', id)
    const commentSnapshot = await ref.get()
    let comments = commentSnapshot
    console.log('comment snapshot')
    console.log(comments[0].comment) //undefined
  } catch (e) {
    console.log(e)
  }

Advertisement

Answer

This returns a QuerySnapshot which contains the DocumentSnapshot of each document that has matched your query.

const commentsSnapshot = await firebase.firestore().collection('comments').where('ytid', '==', id).get()

The array of object is a field in your document. You cannot get a single field from a document. You need to fetch the document and then access that field hence you make that query above first.

Now commentsSnapshot.docs is an array of DocumentSnapshots. Now if you know there is only one matching document you can access it’s data like this:

const firstCommentData = commentsSnapshot.docs[0].data()
//Access a specific field
const anyField = firstCommentData.anyField

In case your QuerySnapshot has multiple documents, you can loop thought the docs as it is an array.

//commentsSnapshot.forEach(...) works as well
commentsSnapshot.docs.forEach((doc) => {
  console.log(doc.data())
})
Advertisement