我正在嘗試獲取所有子集合查詢的父檔案,因此我的資料庫看起來像這樣
/production/id/position/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();
uj5u.com熱心網友回復:
正如 Pierre Janineh 所指出的,您需要使用和類的parent屬性。DocumentReferenceCollectionReference
具體來說,對于每個QueryDocumentSnapshot(“提供與 a 相同的 API 表面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()在回圈中構建的一個或多個承諾陣列(如下所示),但是,根據您需要來自父級的資料量,您還可以對資料進行非規范化并將所需的資料添加到子級來自他們父母和祖父母檔案的資料。
要獲取所有父檔案和祖父檔案的資料,您可以執行以下操作:
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);
您將獲得兩個DocumentSnapshots陣列,您可以從中獲取資料。但是您很可能需要將它們中的每一個與其相應的子/孫檔案聯系??起來......
由于 with Promise.all(),回傳值將按照傳遞的 Promises 的順序排列,您可以使用初始陣列的索引(即回圈querySnapshotwith的順序forEach),但這有點麻煩......
此外,請注意,如果您在其中一個positionhistory子集合中有多個檔案,您將多次訪問相同的父檔案和祖父檔案。您可以維護已獲取的檔案 ID 串列,但這又增加了一些復雜性。
因此,出于所有這些原因,最好分析一下對資料進行非規范化是否更容易/更好,如上所述。
uj5u.com熱心網友回復:
您可以使用QuerySnapshot. 它指向許多QueryDocumentSnapshot實體。
const parent = querySnapshot.ref.parent;
查看Firebase 檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398216.html
標籤:javascript 火力基地 谷歌云firestore
