arrays - Angular Firestore - 从嵌套的引用数组映射数据
问题描述
我有一个集合 A,这些文档有一个对集合 B 中文档的引用数组。
在我的服务中,我得到了所有的 A,但有一系列不可用的对象。但我也想查看它们。
getAs() {
this.aService.getAs().subscribe((data) => {
this.aArray = data.map((e) => {
return {
id: e.payload.doc.id,
...(e.payload.doc.data() as {}),
} as A;
});
//TODO some magic to get a nice array of B's inside every A
});
}
重要的是获取 A 对象数组,其中包含 B 对象数组,而不是 A 和 B 的两个单独数组。
我希望我已经在某种程度上清楚地表达了自己。提前致谢
解决方案
正如 Firestore 文档中所述,Firestore Reference文档引用是指 Firestore 中的文档位置,可用于读取、写入或收听所述文档。这意味着引用类型不存储文档数据,因此您必须查询它。
您需要做的是遍历每个引用array_of_bs
并使用其路径来查询相应的文档。然后,将文档数据添加到一个临时数组中,并将其与 map() 函数返回的数组结合起来,如下所示:
async getAs() {
this.aService.getAs().subscribe(async (data) => {
const promises = await data.map(async (e) => {
// temp array to hold b document data
let array_of_bs = [];
// loop over each reference in array_of_bs
for (const path of (e.payload.doc.data() as any).array_of_bs) {
const bObj = await this.afs.doc(path).get().toPromise();
array_of_bs.push(bObj.data());
}
return {
id: e.payload.doc.id,
...(e.payload.doc.data() as {}),
array_of_bs: array_of_bs // this will overwrite the array_of_bs returned in the above line with the document data
} as A;
});
const docValues = await Promise.all(promises);
console.log(docValues);
});
}
推荐阅读
- react-native - React Native 本地图像显示为灰色背景
- swift - 我可以将 appcenter 与 swift 一起用于反应原生项目吗?
- sql - PLS-00307:与此调用匹配的“X”声明过多
- groovy - Groovy 提取子字符串
- python - 返回密码建议的所有排列的函数
- bash - 在 bash 中对 echo 命令使用文件通配符
- c# - 使用自动映射器手动映射对象列表
- memory - enum和Option的内存表示是什么
? - blazor - 使用 RemoteAuthenticatorView OnLogInSucceeded 提供第二个 AzureAD 登录对话框
- javascript - 嵌套对象的MongoDB聚合过滤