![](/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.