如何获取firestore collectionGroup查询的父文档?

2024-01-15

我正在尝试获取我得到的所有子集合查询的父文档,因此我的数据库看起来像这样

/生产/id/位置/id/positionhistory

我获得了职位历史的所有文件,但我还需要一些职位和生产的数据。我希望是否有一种方法可以在 collectionGroup 查询中获取父母的文档。我也在使用 firestore v9。

const getHistory = async () => {
  setLoading(true);
  try {
    const userHisRef = query(
      collectionGroup(db, "positionhistory"),
      where("userid", "==", currentUser.uid)
    );
    const querySnapshot = await getDocs(userHisRef);
    let arr = [];
    querySnapshot.forEach((doc) => {
      console.log(doc.id);
      arr.push(doc.id);
    });

    setLoading(false);
  } catch (err) {
    console.log(err);
    setLoading(false);
    
  }
};
getHistory();

正如 Pierre Janineh 所指出的,您需要使用parent的属性DocumentReference https://firebase.google.com/docs/reference/js/firestore_.documentreference.md#documentreferenceparent and CollectionReference https://firebase.google.com/docs/reference/js/firestore_.collectionreference#collectionreferenceparent类。

具体来说,对于每个QueryDocumentSnapshot(它“提供与DocumentSnapshot“) 在里面QuerySnapshot你可以做:

const querySnapshot = await getDocs(userHisRef);
let arr = [];
querySnapshot.forEach((doc) => {

  const docRef = doc.ref;   
  const parentCollectionRef = docRef.parent;   // CollectionReference
  const immediateParentDocumentRef = parentCollectionRef.parent; // DocumentReference
  const grandParentDocumentRef = immediateParentDocumentRef.parent.parent; // DocumentReference
  // ...
});

这样您就可以轻松获得DocumentReferences(以及ids) 父母和祖父母的文件。

但是,您想要获取这些父/祖父母文档的一些数据(“我还需要一些来自职位和生产的数据”),这更复杂......因为你实际上需要根据这些文档来查询它们DocumentReferences.

为此你可以使用Promise.all() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all使用您在循环中构建的一个或多个承诺数组(如下所示),但是,根据您需要来自父母的数据量,您还可以对数据进行非规范化并向孩子添加来自其父母的所需数据,以及祖父母文档。

要获取所有父母和祖父母文档的数据,您可以执行以下操作:

const querySnapshot = await getDocs(userHisRef);
let arr = [];

const parentsPromises = [];
const grandparentsPromises = [];

querySnapshot.forEach((doc) => {
  const docRef = doc.ref;   
  const parentCollectionRef = docRef.parent;   // CollectionReference
  const immediateParentDocumentRef = parentCollectionRef.parent; // DocumentReference
  const grandParentDocumentRef = immediateParentDocumentRef.parent.parent; // DocumentReference
  
  parentsPromises.push(getDoc(immediateParentDocumentRef));
  grandparentsPromises.push(getDoc(grandParentDocumentRef));
  // ...
});

const arrayOfParentsDocumentSnapshots = await Promise.all(parentsPromises);
const arrayOfGrandparentsDocumentSnapshots = await Promise.all(grandParentDocumentRef);

你会得到两个数组DocumentSnapshot您可以从中获取数据。但您很可能需要将它们中的每一个与其相应的子/孙文档链接起来......

自从,与Promise.all(),返回的值将按照传递的 Promise 的顺序排列,您可以使用初始数组的索引(即循环的顺序)querySnapshot with forEach)但是有点麻烦……

此外,请注意,如果您在其中之一中有多个文档positionhistory子集合,您将多次获取相同的父级和祖级文档。您可以维护已获取的文档 ID 的列表,但这又增加了一些复杂性。

因此,出于所有这些原因,如果对数据进行非规范化不更容易/更好,最好进行分析,如上所述。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何获取firestore collectionGroup查询的父文档? 的相关文章

随机推荐