我的数据库有一个节的集合,每个节包含一个子节的子集合。
这是我需要创建的数组:
[
{
"sectiontitle": "first section",
"sectiontype": "1",
"__id__": "6jwwukHmOs1743yC13vH",
"subsections": [
{
"desc": "blah blah blah",
"__id__": "KTq4MJTEMbDfR33RoX9J"
},
{
"desc": "blah blah blah",
"__id__": "ASFSADFSAFSADFSADFFS"
}
]
},
{
"sectiontitle": "second section",
"sectiontype": "1",
"__id__": "5jwwDHEDOs1743yC13vG",
"subsections": [
{
"desc": "blah blah blah",
"__id__": "DFG4MJTEMbDfR33DDDDD"
},
{
"desc": "blah blah blah",
"__id__": "ASDFGHFSAFSADFSHJFRD"
}
]
}
]
我的代码是:
// get sections
firebase.firestore().collection("sections").get().then((sections) => {
var myarray = [];
var i = 0;
sections.forEach((section) => {
var sectiondata = section.data();
sectiondata.__id__ = section.id
sectiondata.subsections = [];
myarray.push(sectiondata);
//get subsections
firebase.firestore().collection("sections").doc(sectiondata.__id__).collection("subsections").get().then((subsections) => {
subsections.forEach((subsection) => {
var subsectiondata = subsection.data();
subsectiondata.__id__ = subsection.id;
myarray.push('sections.' + i + '.subsections', subsectiondata); // problem is i index is not correct
});
});
i++;
});
});
此问题是i
索引不正确,因为读取的部分已经完成,并且在读取子部分开始时已遍历foreach。我不熟悉Javascript承诺,所以我希望有人可以帮助我解决该问题?
基本上,为每个部分添加子部分。
谢谢。
答案 0 :(得分:0)
请尝试一下,让我知道是否正确运行。请注意,SubjectBehavior是从RxJs库导入的,我的代码是打字稿代码,正如我认为您使用打字稿一样。
sb = new SubjectBehavior<[]>();
var basicArray = [];
firebase.firestore().collection("sections").get().then((sections) => {
var myarray = [];
basicArray = [];
var count = 0;
sections.forEach((section) => {
var sectiondata = section.data();
sectiondata.__id__ = section.id
sectiondata.subsections = [];
myarray.push(sectiondata);
count++;
if( count === sections.length()) {
sb.next(myarray); //or .emit(), i dont remember
}
//get subsections
});
sb.subscribe( (myArrayElements: any[]) => {
myArrayElement.foreach( (element) => {
firebase.firestore().collection("sections").doc(element.__id__).collection("subsections").get().then((subsections) => {
subsections.forEach((subsection) => {
var subsectiondata = subsection.data();
subsectiondata.__id__ = subsection.id;
basicArray.push('here element data (sectionData)' + '' + '.subsections', subsectiondata);
});
});
});
});
});