首页 > 解决方案 > 我想从 firebase 中的所有用户那里获取帖子 react native

问题描述

我想从 firebase 中的所有用户那里获取帖子。

这是获取代码

const fetchPosts = async () => {
    try {
      const list = [];

      await db
        .collection(`posts/*/userPosts`) // This is the line I want help with...

        .get()
        .then((querySnapshot) => {
          // console.log('Total Posts: ', querySnapshot.size);

          querySnapshot.forEach((doc) => {
            const { userId, post, postImg, likes, comments } = doc.data();
            list.push({
              id: doc.id,
              userId,
              userName: "Test Name",
              userImg:
                "https://lh5.googleusercontent.com/-b0PKyNuQv5s/AAAAAAAAAAI/AAAAAAAAAAA/AMZuuclxAM4M1SCBGAO7Rp-QP6zgBEUkOQ/s96-c/photo.jpg",

              post,
              postImg,
              liked: false,
              likes,
              comments,
            });
          });
        });

      setPosts(list);

      if (loading) {
        setLoading(false);
      }

      console.log("Posts: ", posts);
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    fetchPosts();
  }, []);

我的 firebase cloud firestore 集合在 msg 下方的图像中显示。

这条路径是这样的:/posts/UserUID/userPosts/PostUID

问题是,如果用户添加了一个帖子,它就会像这样保存/posts/UserUID/userPosts/PostUID

所以我想做的就是从所有用户那里获取帖子并呈现它们。喜欢await db.collection(`posts/UserUID/userPosts`) // And there is more but not required for now

这是图片的链接:

工具:JavaScript、Expo、React Native、Firebase、Cloud firestore

标签: javascriptfirebasereact-nativegoogle-cloud-firestoreexpo

解决方案


使用集合组。

代替

await db.collection(`posts/*/userPosts`)

await db.collectionGroup(`userPosts`)

推荐阅读