首页 > 解决方案 > 将 FirestoreCollection 转换为数组?

问题描述

我很难将 Firestore 数据转换为 chart.js 图的数组。

从 Firestore 获取数据

fetchData(){

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

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

创建图表

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,
    }]
  },
    }
)

我现在使用硬编码值[4, 3, 5, 2, 6, 7]作为我的数据点的占位符。我将如何使用来自 Firestore 的值?

解决方案

正如Ohad在下面提到的:

let chartData;

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

这将为您提供一个数组,其中每个文档都在其自己的索引中。您可以像访问任何其他对象(即chartData[0].wheelCount)一样访问单个属性。

标签: javascriptangularchart.jsgoogle-cloud-firestore

解决方案


调用this.updatesCollection.get()将异步返回一个querySnapshot对象。

AquerySnapshot有一个属性,它是一个包含零个或多个对象docs的数组。documentSnapshot这些中的数据可以用该.data()方法提取。

生成数组的代码可能如下所示:

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

推荐阅读