首页 > 解决方案 > 使用文档 ID 从 Firestore 获取数据

问题描述

我的firestore数据库中有两个集合,第一个是所有文档的列表(BlockList),第二个是用户的。当用户在应用程序上为帖子添加书签时,仅将此帖子的 id 发送到子集合(收藏夹)。

那么我如何根据它的 id 显示来自第一个集合的这个子集合的文档。

图 1

图 2

firebaseFirestore.collection("Users")
                .document(userId).collection("Favorites").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<String> list = new ArrayList<>();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        list.add(document.getId());
                    }
                    Log.d(TAG, list.toString());
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

我使用此代码到达子集合 ID 的列表,但我想知道如何使用它从主集合(BlockList)中获取适合此 ID 的文档。

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


在循环之后,您已经有了一个 id 列表,只需遍历它们并在blockedList 中找到它们:

....
....
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}

//here loop through the list

for(int i = 0 ; i<list.size() ; i++){

//now refer to the id in the blocked list
firebaseFirestore.collection("BlockList").document(list.get(i)).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {

    .........

    });



}

......
......

推荐阅读