[英]How can I get all the documents of a all parent collections asynchronously from firebase firestore?
I'm trying to get all the documents from all the collections from a firestore database which looks something like this:我正在尝试从看起来像这样的 firestore 数据库中的所有 collections 中获取所有文档:
-users(collection)
-user1 (document)
-snippets(collection)
-snippetdId1 (document)
-snippetdId2 (document)
-user2 (document)
-snippets (collection)
-snippetdId1 (document)
-snippetdId2 (document)
-snippetdId3 (document)
let allSnippets = [];
firebase
.firestore()
.collection("users")
.get()
.then((snapshot) => {
snapshot.docs.forEach(async (element) => {
const snippets = await firebase
.firestore()
.collection("users")
.doc(element.id)
.collection("snippets")
.get();
snippets.forEach(
async (snippet) => await allSnippets.push(snippet.data())
);
});
console.log(allSnippets); // [](length 0, but has all the elements inside)
});
The problem I'm having is that the 'allSnippets' array has a length of 0 but it has all the elements that I want, I know the problem is with synchronicity but I don't know how to solve it.我遇到的问题是“allSnippets”数组的长度为 0,但它包含我想要的所有元素,我知道问题在于同步性,但我不知道如何解决它。 I've tried using.then instead but is the same thing, length 0 but has all the elements inside.
我尝试过 using.then 但它是相同的东西,长度为 0 但里面有所有元素。
The problem is that the console.log(allSnippets)
runs before any of the allSnippets.push(snippet.data()
has run. If you add some more logging, or run the code in a debugger, you can easily see this.问题是
console.log(allSnippets)
在任何allSnippets.push(snippet.data()
运行之前运行。如果您添加更多日志记录,或者在调试器中运行代码,您可以轻松看到这一点。
Normally, you'd use Promise.all
to wait until all the get()
calls for the snippets are done.通常,您会使用
Promise.all
等到对片段的所有get()
调用完成。 But here there's actually an easier way.但这里实际上有一个更简单的方法。 Since you want to get all snippets from all users, you can use a collection group query .
由于您想获取所有用户的所有片段,您可以使用集合组查询。 With that, the entire code is reduced to:
这样,整个代码就简化为:
firebase.firestore()
.collectionGroup("snippets")
.get()
.then((snippetsSnapshot) => {
const snippets = snippetsSnapshot.docs.map(doc => doc.data());
console.log(snippets);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.