Reputation: 181
I have a question regarding Firestore, I created a "category" collection in which I have several documents, I created a "construction sites" sub-collection! I want to retrieve all my sub collections from each category, but when I try to do like this:
useEffect(() => {
const listConstruction = [];
db.collection('category').get().then((collectionCategory) => {
collectionCategory.forEach((doc) => {
doc.ref.collection('construction').get().then((collectionConstruction) => {
collectionConstruction.forEach((doc1) => {
listConstruction.push({
idCategory: doc.id,
libelleCategory: doc.data().libelle,
title: doc1.data().title,
description: doc1.data().description,
});
});
});
});
}).finally(() => {
setConstruction(listConstruction);
});
}, []);
The problem is that it hasn't finished pushing the constructs it passes into my finally!
Having no experience with NoSQL and Firestore yet, I would have liked if I'm not completely wrong about its use and if so how to fix it?
Upvotes: 4
Views: 6632
Reputation: 83191
If I correctly understand your problem, you need to use a Collection Group query.
As explained in the doc:
A collection group consists of all collections with the same ID. By default, queries retrieve results from a single collection in your database. Use a collection group query to retrieve documents from a collection group instead of from a single collection.
Side note: If you want to call asynchronous methods in a forEach
loop, you should use Promise.all()
.
Upvotes: 5