0

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)
  }
3
  • 1
    It is definitely possible to get an array. You're currently getting a collection, but not correctly addressing the documents inside. You may want to look at firebase.google.com/docs/firestore/query-data/… Commented May 30, 2021 at 5:14
  • @jnpdx you are right, need to somehow create an object and push the object into the array of objects. Commented May 30, 2021 at 5:42
  • Can you please share a screenshot of how your Firestore doc looks ? Commented May 30, 2021 at 6:50

2 Answers 2

2

I have figured it out. I did it like below and it works.

  let comments = []
  try {
    const ref = firebase
      .firestore()
      .collection('comments')
      .where('ytid', '==', id)
    const commentSnapshot = await ref.get()
    commentSnapshot.forEach((doc) => {
      var obj = {}
      obj['comment'] = doc.data().comment
      obj['createdat'] = doc.data().createdat
      obj['username'] = doc.data().username
      obj['name'] = doc.data().name
      obj['photourl'] = doc.data().photourl

      comments.push(obj)
    }) 
Sign up to request clarification or add additional context in comments.

Comments

1

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())
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.