【问题标题】:Firestore: How to iterate through some documents and get the sub collections?Firestore:如何遍历一些文档并获取子集合?
【发布时间】:2020-11-13 16:45:37
【问题描述】:

目前我正在从基于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]);

我现在有一个 propertyIds 数组,需要对每个 propertyId 重复相同的过程

我应该如何遍历每个propertyId并将所有公司存储在一个变量中,然后最后更新状态?

我尝试使用 Promise.all 但我认为我做得不对。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore promise async-await


    【解决方案1】:

    以下几行应该可以解决问题:

    //...
    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);
            //...
        });
    

    我们使用get() 方法来执行查询并返回一个用QuerySnapshot 解析的promise,而不是使用onSnapshot() 来附加一个QuerySnapshot 事件的侦听器-> 然后我们可以使用Promise.all()

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 2019-11-13
      • 1970-01-01
      • 2022-07-11
      • 1970-01-01
      • 2021-08-26
      • 2023-03-18
      • 2019-10-06
      • 2018-04-09
      相关资源
      最近更新 更多