Reputation: 587
I have a collection in firestore called 'steps' and inside steps collection I have lots of documents and subcollections called 'substeps' in each steps document. I need to create array which will have all the steps and substeps inside that I could use this component, so the array should look like this
let steps = [
{
step: 1,
id: '1'
substeps: [
{
step: '1.1'
substeps: [
{
step: '1.1.2'
}
]
}
]
}
]
Now I want to crate recursive functions with will fetch all the substeps if they are exists
I tried to create function which should fetch all the subcollections, but I don't know how to finish it, so below example of what I tried, but notice function not finished and it is only first steps Here is documentation
fetchAllStepsDeep (request) {
//this.steps = array of objects with step data
let result = []
let requestLocal = this.$firebaseFirestore.collection('steps_for_classes')
for (let i in this.steps) {
result.push(this.steps[i])
requestLocal.doc(this.steps[i].id).get().then((doc) => {
if (doc.exists) {
console.log('Document data:', doc.data())
} else {
// doc.data() will be undefined in this case
console.log('No such document!')
}
}).catch((error) => {
console.log('Error getting document:', error)
})
}
}
Can someone help me to retrieve all the subcollections inside collection and create one big array with other child arrays of objects? I use vue framework, so maybe this can be helpful
Thanks
Upvotes: 1
Views: 1438
Reputation: 393
If interested in Firestore 9 you can do it by array of strings:
let pathSegment: string[] = [parentKey, "comments"]
doc(db, "channels", channelKey, "comments", ...pathSegments, commentKey)
Upvotes: 0
Reputation: 598688
If the subcollection is always called substeps
, you can create a helper function to handle the recursion
function getSubstepsOf(docRef, path, result) {
docRef.collection("substeps").get((querySnapshot) => {
querySnapshot.forEach((doc) => {
result.push({ path, doc });
getSubstepsOf(doc.ref, `${path}/substeps/${doc.id}`, result);
});
});
}
And then call it with this from your existing code:
getSubstepsOf(doc.ref, doc.id, result);
Upvotes: 1