![](/img/trans.png)
[英]Get parent document for each item in Firebase collectionGroup
[英]How to get parent document of firestore collectionGroup query?
我正在嘗試獲取我得到的所有子集合查詢的父文檔,所以我的數據庫看起來像這樣
/production/id/position/id/positionhistory
我得到了 position 歷史的所有文件,但我還需要來自 position 和生產的一些數據。 我希望是否有辦法在 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 所指出的,您需要使用DocumentReference
和CollectionReference
類的parent
屬性。
具體來說,對於 QuerySnapshot 中的每個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
(和id
)。
但是,您想獲取這些父/祖父文檔的一些數據(“我還需要來自 position 和生產的一些數據”),這更復雜......因為您實際上需要根據它們的DocumentReference
查詢這些文檔.
為此,您可以使用Promise.all()
和您在循環中構建的一個或多個 arrays 承諾(如下所示),但是,根據您需要多少來自父母的數據,您還可以對數據進行非規范化並添加從他們的父母和祖父母文檔中向孩子們提供所需的數據。
要獲取所有父母和祖父母文檔的數據,您可以執行以下操作:
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
的兩個 arrays ,您可以從中獲取數據。 但是您很可能需要將它們中的每一個與相應的子/孫文檔鏈接起來......
由於使用Promise.all()
,返回的值將按照 Promises 傳遞的順序排列,因此您可以使用初始數組的索引(即使用forEach
querySnapshot
的順序),但這有點麻煩...這就是為什么分析數據的非規范化是否更容易/更好的原因,如上所述。
您可以使用QuerySnapshot
。 它指向許多QueryDocumentSnapshot
實例。
const parent = querySnapshot.ref.parent;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.