Home > Software engineering >  How to get parent document of subcollection in a snapshot listener?
How to get parent document of subcollection in a snapshot listener?

Time:09-12

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!

CodePudding user response:

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

const parentRef = doc.ref.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.

  • Related