Geekr
Geekr

Reputation: 13

Get data from firestore using document id

I have two collections in my firestore database, the first is list of all the documents (BlockList), and the second for the users. when the user bookmark post on the app, send only the id of this post to sub-collection (Favourites).

so how can i display this sub-collection's documents from the first collection based on its ids.

image 1

image 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());
                }
            }
        });

I Use this code to reach the list of the sub-collection ids, but i want to know how to use it to get the documents that appropriate to this ids from the main collection(BlockList).

Upvotes: 0

Views: 2042

Answers (2)

Hasan Bou Taam
Hasan Bou Taam

Reputation: 4035

After the loop you already have a list of the ids, just loop through them and find them in 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) {

    .........

    });



}

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

Upvotes: 1

Mehmet Agah Balbay
Mehmet Agah Balbay

Reputation: 69

    userRef.document(reference)
                    .collection(favCollect)
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                task.getResult()
                                        .getQuery()
                                        .addSnapshotListener((queryDocumentSnapshots, e) -> {
List<DocumentChange> documentChanges = queryDocumentSnapshots.getDocumentChanges();
                                    for (int i = 0; i < documentChanges.size(); i++) {

}

}

In this way you can reach the id you are looking for

Upvotes: 0

Related Questions