2017-10-16 130 views
1

比方说,我有一个userSnapshot我所用get操作有:Firestore - 如何从DocumentSnapshot获取集合?

DocumentSnapshot userSnapshot=task.getResult().getData(); 

我知道我能够从documentSnapshot得到field像这样(例如):

String userName = userSnapshot.getString("name"); 

它只是帮助我获得fields的值,但如果我想在此userSnapshot下获得collection?例如,其friends_listcollection其中包含documents的朋友。

这可能吗?

回答

0

Cloud Firestore中的查询很浅。这意味着当您在get()文件中不能下载子集合中的任何数据时。

如果你想获得的子集的数据,你需要做第二个请求:

// Get the document 
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { 
    @Override 
    public void onComplete(@NonNull Task<DocumentSnapshot> task) { 
     if (task.isSuccessful()) { 
      DocumentSnapshot document = task.getResult(); 

      // ... 

     } else { 
      Log.d(TAG, "Error getting document.", task.getException()); 
     } 
    } 
}); 

// Get a subcollection 
docRef.collection("friends_list").get() 
     .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { 
      @Override 
      public void onComplete(@NonNull Task<QuerySnapshot> task) { 
       if (task.isSuccessful()) { 
        for (DocumentSnapshot document : task.getResult()) { 
         Log.d(TAG, document.getId() + " => " + document.getData()); 
        } 
       } else { 
        Log.d(TAG, "Error getting subcollection.", task.getException()); 
       } 
      } 
     });