正如 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
// ...
});
这样您就可以轻松获得DocumentReference
s(以及id
s) 父母和祖父母的文件。
但是,您想要获取这些父/祖父母文档的一些数据(“我还需要一些来自职位和生产的数据”),这更复杂......因为你实际上需要根据这些文档来查询它们DocumentReference
s.
为此你可以使用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 的列表,但这又增加了一些复杂性。
因此,出于所有这些原因,如果对数据进行非规范化不更容易/更好,最好进行分析,如上所述。