简体   繁体   English

如何在快照侦听器中获取子集合的父文档?

[英]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?我应该在下面的代码中用什么替换 XXXXXXXXXXX?

  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.但是当我像上面那样收听整个 state 时,我做不到。

Thanks for any hint!感谢您的任何提示!

If doc is a DocumentSnapshot object, then you can get a DocumentReference of its parent like this:如果docDocumentSnapshot object,那么您可以像这样获得其父级的DocumentReference

const parentRef = doc.ref.parent.parent;

You can then pass that to getDoc() .然后,您可以将其传递给getDoc() There is no need to build another DocumentReference with doc() .无需使用doc()构建另一个 DocumentReference。

This works for all DocumentSnapshot objects.这适用于所有 DocumentSnapshot 对象。 It is not special to the method you used to get the DocumentReference.它对您用于获取 DocumentReference 的方法并不特殊。 Be sure to use the linked API reference to discover how to use various objects you get back from the Firestore API.请务必使用链接的 API 参考来了解如何使用从 Firestore API 返回的各种对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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