I'm playing around trying to learn Firestore and I'm experiencing some issues regarding joining data from a collection and a sub-collection. The name of the sub-collection is known players
.
-match_stats (collection)
|_ document with random ID
|_ map (field - string)
|_ scorehome (field - Number)
|_ scoreaway (field - Number)
|_ Sub-collection (named: Players)
|_ documents with random ids
|_ Field (Player names, ex. Christopher)
|_ playerkills
|_ playerdeaths
I've been able to console.log
each collection separately, but I want the collection and the sub collection to be included in the same object, so I can combine the data. I'm also open to other suggestions on how to solve this problem.
firebase.initializeApp(firebaseConfig); const db = firebase.firestore(); export default { data() { return { matchInfo: [], }; }, methods: { readMatches() { this.matchInfo = []; db.collection("match_stats").get().then(matchQuerysnapshot => { matchQuerysnapshot.docs.forEach(doc => { console.table(doc.data()); db.collection("match_stats").doc(doc.id).collection("players").get().then(playersQuerySnapshot => { playersQuerySnapshot.docs.forEach(doc => { console.table(doc.data()); }) }) }) }) }, }, mounted() { this.readMatches(); }, };
You could do as follows. First you get all the parent documents and at the same time you use Promise.all() to query, in parallel, all the players
sub-collections.
var db = firebase.firestore();
var promises = []
db.collection('match_stats').get()
.then(snapshot => {
snapshot.forEach(doc => {
...
promises.push(doc.ref.collection('players').get());
})
return Promise.all(promises);
})
.then(results => {
results.forEach(querySnapshot => {
querySnapshot.forEach(function (doc) {
console.log(doc.id, " => ", doc.data());
});
});
});
Note that the order of the results
array is exactly the same than the order of the promises
array.
I based my answer on this similar question making changes to adapt to your question.
Fire store has its own hook for grabbing data while page loads.
data() {
return {
matchInfo: [],
};
},
firestore() {
return {
matchInfo: db.collection('players')
... The rest of your code ...
}
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.