简体   繁体   English

Firestore:如何遍历一些文档并获取子 collections?

[英]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.

相关问题 在 Firestore 中获取子集合的文档 - Fetching documents of sub-collections in firestore 如何在等待时遍历 Firestore 快照文档 - How to iterate through a Firestore snapshot documents while awaiting 如何在Cloud Firestore(Web)中获取所有不带名称的集合和文档 - How to get all collections and documents without their names in Cloud Firestore (web) 如何获取所有 Firestore Collections 和文档? | 反应JS - How to Get all Firestore Collections and Documents? | React JS 如何从 Cloud Firestore 删除集合及其所有子集合和文档 - How to delete a collection with all its sub-collections and documents from Cloud Firestore 如何访问firestore中单个集合中多个文档的子集合? - How to access sub-collections across multiple documents within a single collection in firestore? 如何获取 Firestore (v9) 子集合中的所有文档 - How to get all documents in Firestore (v9) sub collection 获取 Firestore 中包含子集合的所有集合 - Get all collections with sub-collection in Firestore 如何从文档没有数据但只有子 collections 的集合中获取文档 ID 的 Firebase 数组? - How to get Firebase array of documents ids from colletion where documents have No Data but only sub collections? 是否可以通过 firebase CLI 创建 Firestore 集合/文档? - is it possible to create firestore collections/documents through firebase CLI?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM