简体   繁体   中英

How to get parent document of subcollection in a snapshot listener?

I have a snapshot listener attached to a subcollection (this subcollection logs all changes to parent documents). For each document in this subcollection, I want to retrieve the parent docuemnt. What should I replace XXXXXXXXXXX with in my code below?

  const unsubToProfilesRecentlyUpdatedByUser = onSnapshot(qChangedByThisUser, (querySnapshot) => {
    store.state.currentProfileList = [];
    querySnapshot.forEach((doc) => {

      const parentProfileRef = doc(db, "profiles", XXXXXXXXXXX);
      //Get the parent Profile of this Activitylog
      getDoc(parentProfileRef)
        .then((profileSnap) => {
          //store resulting profile in object
          let profile = profileSnap.data()
          profile.id = profileSnap.id

          store.state.currentProfileList.push(profile)
        })

    });
    //console.log("Current cities in CA: ", cities.join(", "));
  });

I have tried many examples from other posts, and I manage to make it work when listening only to changes, in which case it is

const parentProfileRef = doc(db, "profiles", change.doc.ref.parent.parent.id);

But I can't make is work when listening to the whole state like above.

Thanks for any hint!

If doc is a DocumentSnapshot object, then you can get a DocumentReference of its parent like this:

const parentRef = doc.ref.parent.parent;

You can then pass that to getDoc() . There is no need to build another DocumentReference with doc() .

This works for all DocumentSnapshot objects. It is not special to the method you used to get the DocumentReference. Be sure to use the linked API reference to discover how to use various objects you get back from the Firestore API.

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