问题
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