Convert FirestoreCollection into an array?

◇◆丶佛笑我妖孽 提交于 2020-06-25 00:58:40

问题


I'm having difficulty converting the Firestore data into an array for the chart.js graph.

Getting the data from Firestore

fetchData(){

    //Get data
    this.updatesCollection = this.afs.collection(pathStats);

    this.updates = this.updatesCollection.valueChanges();
}

Creating the Chart

createChart(){

this.chart = new Chart('canvas', {
  type: 'line',
  data: {
    labels: ['5/18/18', '5/19/18', '5/20/18', '5/21/18', '5/22/18', '5/23/18'],
    datasets: [{
      label: 'Filled',
      backgroundColor: 'gray',
      data: [4, 3, 5, 2, 6, 7],
      fill: true,
    }]
  },
    }
)

I'm using the hard-coded values [4, 3, 5, 2, 6, 7] right now as a placeholder for my data points. How would I use the values coming from Firestore instead?

Solution

As mentioned by Ohad below:

let chartData;

this.updatesCollection.ref.get().then((querySnapshot) => {
    chartData = querySnapshot.docs.map(doc => doc.data());
}

This gets you an array with each document in it's own index. You can access individual properties like any other object (ie chartData[0].wheelCount).


回答1:


Calling this.updatesCollection.get() will asynchronously return a querySnapshot object.

A querySnapshot has a docs property which is an array containing zero or more documentSnapshot objects. The data in these can be extracted with the .data() method.

The code for producing your array could look like this:

let chartData = this.updates.collection.get()
  .then(querySnapshot => {
    chartData = querySnapshot.docs.map(doc => doc.data())
  })


来源:https://stackoverflow.com/questions/50519999/convert-firestorecollection-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!