[英]Joining collection and sub-collection in firestore (web)
我正在尝试学习 Firestore,但在连接集合和子集合中的数据时遇到了一些问题。 子集的名称是已知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
我已经能够分别对每个集合进行console.log
,但我希望集合和子集合包含在同一个 object 中,因此我可以合并数据。 我也愿意接受有关如何解决此问题的其他建议。
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(); }, };
你可以这样做。 首先,您获得所有父文档,同时使用 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());
});
});
});
请注意, results
数组的顺序与promises
数组的顺序完全相同。
我的回答基于这个类似的问题,并进行了更改以适应您的问题。
Fire store 有自己的钩子,用于在页面加载时抓取数据。
data() {
return {
matchInfo: [],
};
},
firestore() {
return {
matchInfo: db.collection('players')
... The rest of your code ...
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.