简体   繁体   中英

Firebase Cloud Firestore follow reference

I've gotten a queryDocumentSnapshot with the following code:

mFireStore = FirbaseFirestore.getInstance();
mFireStore.collection("myCollection").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
                    if (doc.getType() == DocumentChange.Type.ADDED) {
                        // Set some data from the doc.getDocument here

mFireStore.collection("myCollection").document(doc.getDocument().getId()).collection("subCollection").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                                    @Override
                                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                                        if (queryDocumentSnapshots.isEmpty()){
                                            // not found
                                        } else{

                                            List<DocumentSnapshot> hosts = queryDocumentSnapshots.getDocuments();

                                            for (int i = 0; i < hosts.size(); i++){
                                                // Each hosts DocumentSnapshot has a "host" field which contains a reference to a document
                                                // I'd like to follow this reference and get that document
                                            }
                                        }
                                    }
                                });

My issue is that once I've gotten the list of host DocumentSnapshots , I'd like to follow their "host" field which contains a reference to a document. I would like to follow this reference and get the document at the other end but do not know how. If you notice any other problems with my logic, feel free to point it out as I am very new to Cloud Firestore.

To solve this, you can simply iterate over the hosts list. If your host field holds the reference as a String , then please use the following lines of code:

for (DocumentSnapshot ds : hosts) {
    String host = ds.getString("host");
    Log.d("TAG", host);
}

If your host field holds the reference as a DocumentReference , then please use the following line of code:

DocumentReference host = ds.getDocumentReference("host");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM