将FirestoreCollection转换为数组?

Fir*_*nks 5 javascript chart.js angular google-cloud-firestore

我在将Firestore数据转换为chart.js图的数组时遇到困难。

从Firestore获取数据

fetchData(){

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

    this.updates = this.updatesCollection.valueChanges();
}
Run Code Online (Sandbox Code Playgroud)

创建图表

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,
    }]
  },
    }
)
Run Code Online (Sandbox Code Playgroud)

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

如以下Ohad所述:

let chartData;

this.updatesCollection.ref.get().then((querySnapshot) => {
    chartData = querySnapshot.docs.map(doc => doc.data());
}
Run Code Online (Sandbox Code Playgroud)

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

Oha*_*had 5

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

querySnapshot具有docs属性,该属性是含有零个或多个阵列documentSnapshot对象。可以使用该.data()方法提取其中的数据。

用于生成数组的代码如下所示:

let chartData = this.updates.collection.get()
  .then(querySnapshot => {
    chartData = querySnapshot.docs.map(doc => doc.data())
  })
Run Code Online (Sandbox Code Playgroud)