pma*_*ing 7 promise async-await firebase google-cloud-firestore
我试图找出一种方法来获取文档集合及其子集合数据。
例如,我的树是...
-locations
-{locationId}
-historic
-april
-airTemp: 12.4
-displayOrder: 4
-august
-airTemp: 14.5
-displayOrder: 9
-december
-airTemp: 13.5
-displayOrder: 12
etc..
Run Code Online (Sandbox Code Playgroud)
... wherelocationId
是文档,historic
是包含每月文档的子集合。
我知道如何获取顶级集合项并将其存储到数组中,但我也想将它们的子集合数据(即 jan、feb 等)添加到每个文档中。
var locations = []
let ref = db.collection('locations')
db.collection('locations').get()
.then(snapshot => {
snapshot.forEach(doc => {
let location = doc.data()
location.id = doc.id
location.name = doc.name
// get the historic subcollection data here
})
})
Run Code Online (Sandbox Code Playgroud)
如何从每个对象中获取组合数据(集合和子集合),然后将其推送到数组中?
赏金是错误的结构, 每个月都应该是它自己的对象
移动/网络客户端库无法在一次查询中获取获取Firestore 文档的数据及其子集合文档的数据。
甚至无法获取文档子集合的列表(使用移动/网络客户端库),请参阅https://firebase.google.com/docs/firestore/query-data/get-data#文档子集合列表
因此,您需要知道子集合的名称才能查询它们,这就是您的情况(name = 'historic')。
你可以这样做。首先,您获取所有父文档,同时用于Promise.all()
并行查询所有“历史”子集合。
var db = firebase.firestore();
var promises = []
db.collection('locations').get()
.then(snapshot => {
snapshot.forEach(doc => {
let location = doc.data()
location.id = doc.id
location.name = doc.data().name
console.log(location);
promises.push(doc.ref.collection('historic').get());
})
return Promise.all(promises);
})
.then(results => {
results.forEach(querySnapshot => {
querySnapshot.forEach(function (doc) {
console.log(doc.id, " => ", doc.data());
});
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,数组的顺序results
与数组的顺序完全相同promises
。
另请注意,要获取文档项(例如)的值,name
您需要执行doc.data().name
而不是执行doc.name
。
归档时间: |
|
查看次数: |
2887 次 |
最近记录: |