I`m using Firestore as database and VueJS as Javascript framework.
The goal:
I got one collection where all fotball players are represented by individual documents. I get a list of all available fotball players.
Get all statistics that exists on available fotball players.
Combine (aggregate) all statistics for per fotball player for all matches played.
The problem is that this.aggregatedPlayerStats returns as an empty array. I suspect it has to do with asynchronous code, as it works if I trigger the aggregatePlayerStats() method on a button.
Code:
export default {
name: "AggregatedAllTimeStats",
data() {
return {
allPlayers: [],
allStats: [],
aggregatedPlayerStats: []
};
},
async created() {
await this.getAllPlayers();
await this.getAllStats();
this.aggregatePlayerStats();
},
methods: {
async getAllPlayers() {
return db.collection("players").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.allPlayers.push({
playerid: doc.id,
name: doc.data().name,
playerstatus: doc.data().playerstatus
})
})
})
},
getAllStats() {
this.allPlayers.forEach((player) => {
return db.collection("playerstatsformatch").where("playerid", "==", player.playerid).get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.allStats.push(doc.data())
})
})
})
},
aggregatePlayerStats() {
const aggregatedResults = Object.values(
this.allStats.reduce((a, c) => {
if (!a[c.playerid]) {
a[c.playerid] = {
goals: c.goals,
name: c.name,
assists: c.assists
};
} else {
a[c.playerid].goals += c.goals;
}
return a;
}, {})
);
this.aggregatedPlayerStats = aggregatedResults
console.log(this.aggregatedPlayerStats)
}
},
};
async, anawaitis expected rather than a.then.