是否可以在不向 .get()
方法提供参数的情况下查询 Firestore 中的嵌套文档?
我想通过遍历所有用户 ID 并获取所有用户帖子来获取所有用户创建的所有帖子。
以下是我使用的代码。
非常感谢。
getAllPosts() {
final CollectionReference postsRef = FirebaseFirestore.instance
.collection("posts");
var allPosts = postsRef.get().then((value) =>
value.docs.forEach((snapshot) {
var userPostsRef = postsRef.doc(snapshot.id);
var subCollection = userPostsRef.collection("userPosts").get();
print("subCollection $subCollection");
})
);
print("allPosts $allPosts");
}
print("subCollection $subCollection");
不会在控制台上显示任何内容。
print("allPosts $allPosts");
在控制台上显示 “未来”的实例。
Firestore 结构:
posts -> userId -> userPosts -> postId -> {实际的帖子文档}
答案 0 :(得分:1)
您正在寻找 collectionGroup
查询。
FirebaseFirestore.instance
.collectionGroup('userPosts')
.get((snpashot) {
print(snapshot.size)
});
这将从名为“userPosts”的所有子集合中获取所有文档,即来自所有用户文档的 userPosts。然后,您可以稍后根据需要使用 Dart 通过用户 ID 过滤它们。