[英]Joining collection and sub-collection in firestore (web)
I'm playing around trying to learn Firestore and I'm experiencing some issues regarding joining data from a collection and a sub-collection.我正在尝试学习 Firestore,但在连接集合和子集合中的数据时遇到了一些问题。 The name of the sub-collection is known
players
.子集的名称是已知
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.我已经能够分别对每个集合进行
console.log
,但我希望集合和子集合包含在同一个 object 中,因此我可以合并数据。 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.首先,您获得所有父文档,同时使用 Promise.all() 并行查询所有
players
子集合。
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.请注意,
results
数组的顺序与promises
数组的顺序完全相同。
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. Fire store 有自己的钩子,用于在页面加载时抓取数据。
data() {
return {
matchInfo: [],
};
},
firestore() {
return {
matchInfo: db.collection('players')
... The rest of your code ...
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.