[英]Firestore: How to iterate through some documents and get the sub collections?
Currently I am loading all companies from a property based on propertyId
, as shown below from firestore:目前我正在从基于
propertyId
的属性中加载所有公司,如下图所示:
useEffect(() => {
const loadCompanies = () => {
try {
setLoading(true);
return firebase
.firestore()
.collection(`/properties/${user.propertyId}/companies`)
.orderBy('companyName', 'asc')
.onSnapshot((querySnapshot) => {
const allCompanies = [];
querySnapshot.forEach((doc) => {
allCompanies.push({
id: doc.id,
...doc.data(),
});
});
setCompanies(allCompanies);
setLoading(false);
});
} catch (error) {
console.log(error);
setError(error.message);
}
};
if (user) {
return loadCompanies();
}
}, [user]);
I have an array of propertyIds
now and need to repeat the same process for each propertyId
我现在有一个
propertyIds
数组,需要对每个propertyId
重复相同的过程
How should I iterate through each propertyId
and store all companies in one variable and then update the state in the end?我应该如何遍历每个
propertyId
并将所有公司存储在一个变量中,然后最后更新 state?
I tried to use Promise.all but I think I am not doing it right.我尝试使用 Promise.all 但我认为我做得不对。
Something along the following lines should do the trick:以下几行应该可以解决问题:
//...
const firestore = firebase.firestore();
const propertyIds = ['p1', 'p2'];
const promises = [];
const allCompanies = [];
propertyIds.forEach(propID => {
promises.push(firestore.collection(`/properties/${propId}/companies`).orderBy('companyName', 'asc').get());
});
Promise.all(promises)
.then(querySnapshotArray => {
querySnapshotArray.forEach(querySnapshot => {
querySnapshot.forEach((doc) => {
allCompanies.push({
id: doc.id,
...doc.data(),
});
});
});
setCompanies(allCompanies);
//...
});
Instead of using onSnapshot()
which attaches a listener for QuerySnapshot events, we use the get()
method, which executes the query and returns a promise that resolves with a QuerySnapshot
-> we can then use Promise.all()
.我们不使用为 QuerySnapshot 事件附加侦听器的 onSnapshot
onSnapshot()
) 方法,而是使用get()
方法,该方法执行查询并返回 promise,该 promise 使用QuerySnapshot
解析 -> 然后我们可以使用Promise.all()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.