【问题标题】:How to get subcollections of a filtered collection item in firestore?如何在firestore中获取过滤集合项的子集合?
【发布时间】:2021-01-15 13:07:00
【问题描述】:

我有一个集合,它在单个项目中也有子集合。我过滤集合,然后尝试访问过滤后的第一项的子集合。我尝试使用 foreach 循环来做到这一点。但是没有更简单的直接方式,例如给出直接路径吗?我该怎么做?

示例数据路径通过:/users/O2Am1XSXBOOWOQj2pzyu/appointments

这是我的代码:

useEffect(()=>{

  var currentUser = auth().currentUser;
    if (currentUser) {

        setFoundUser(currentUser);

        firestore().collection('users').where('phone','==',currentUser.phoneNumber).get()
        .then(function (querySnapshot) {
            
            if(!querySnapshot.empty){
              
                setFoundUser(querySnapshot.docs[0])

                firestore().collection('users/'+querySnapshot.docs[0].id+'/appointments').get()
                .then(function (appointmentsSnapshot) {
                  
                    var appointmentsArray=[]

                    if(appointmentsSnapshot!=undefined && !appointmentsSnapshot.empty){

                      console.log('say: '+appointmentsSnapshot.docs.length)

                      appointmentsSnapshot.forEach(function(s){
                        
                        firestore().doc(s.data().aref).get()
                        .then(function (appiSnapshot) {
                            if(appiSnapshot!=undefined&&!appiSnapshot.empty){

                              console.log('appi: '+appiSnapshot.docs.length)
                              appointmentsArray.push({id:appiSnapshot.id, data:appiSnapshot.data()})
                            }

                        });
                        setAppointments(appointmentsArray)
                      });

                    }

                    
                });

            }

        });
    }

},[])

【问题讨论】:

  • 请编辑问题以解释此代码的工作方式与您期望的不同,或者提供更多关于您遇到的具体问题的详细信息。请记住,我们看不到您的数据库或代码中的任何变量值。
  • 我用foreach循环来做有没有更方便的方法?
  • 如果您解释一下您的最终目标,并说明您希望使用的数据,这将很有帮助。仔细观察几十行代码可能很难弄清楚它要做什么。

标签: javascript firebase react-native google-cloud-firestore


【解决方案1】:

您需要执行一个循环来从您的集合中获取子集合数据,最好的方法确实是一个forEach 循环。如官方文档here 中所述,您的操作方式与您的非常相似。如果您知道要获取子集合的文档,如何执行此操作的代码示例如下。

var query = db.collection("users").where("field", "==", "O2Am1XSXBOOWOQj2pzyu");
query.get().then((querySnapshot) => {
  querySnapshot.forEach((document) => {
    document.ref.collection("appointments").get().then((querySnapshot) => {
      ...
    });
  });
});

该查询与您的查询非常相似,只是减少了几行您不需要的行。此代码基于 Google 的 Firebase 工程师提供的答案,您可以查看here

总而言之,您正在做正确的事情并推荐用于子集合,因为使用它们并不是那么简单,您需要遵循这些特定要求才能获取所需的信息。您还可以在这篇精彩的文章here 上阅读有关子集合的更多详细信息并获取它们的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多