简体   繁体   中英

How to find the parent collection to a document in Firebase Firestore?

I'm searching a subquery in Firebase and I'm trying to find the parent collection (and then the parent document) it is a part of. Here is my code

let queryRef = orgRef.where('User_ID', '==', userID).get()
    .then(snapshot => {
        if (snapshot.empty) {
          console.log('No matching documents.');
          return;
        }  



        snapshot.forEach(doc => {
          console.log(doc.parent());
        });
      })
      .catch(err => {
        console.log('Error getting documents', err);
      });

however using doc.parent, or snapshot.parent doesn't work. How do I find the parent documents of the subcollection?

If you have a DocumentSnapshot object, you will want to use its ref property to get a DocumentReference object that points to it. DocumentReference has a parent property that will get you the collection where the document lives. So, you will probably want:

doc.ref.parent

For any given doc in the query results.

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