在查询父集合cloud firestore的基础上获取子集合

问题描述 投票:0回答:1

我想在查询父集合后获取子集合中的所有文档 我想访问“关注”集合中的所有文档,因为您只能看到登录用户的屏幕截图

这是我的代码

const getFollowers = async () => {
      const q = query(collection(db, "users"), where("uid", "==", user.uid));
      const querySnapshot = await getDocs(q, "follow");
      const data = [];
      querySnapshot.forEach((doc) => {
        data.push({ id: doc.id, data: doc.data() });
        // console.log(doc.id, " => ", doc.data());
        setFollowingUsers(data);
      });      
    };

这是我的数据库截图

reactjs firebase google-cloud-firestore collections
1个回答
0
投票

需要先查询用户doc,再查询子集合,如下(未经测试):

const q = query(collection(db, "users"), where("uid", "==", user.uid));
const querySnapshot = await getDocs(q);
if (querySnapshot.size > 0) {
  const userDocSnapshot = querySnapshot[0];
  const qFollowers = query(collection(db, "users", userDocSnapshot.id, "follow));
  const querySnapshot = await getDocs(qFollowers);
  const data = [];
  querySnapshot.forEach((doc) => {
  data.push({ id: doc.id, data: doc.data() });
     setFollowingUsers(data);  
  });      
}

请注意,

getDocs(q, "follow");
无法工作,请参阅文档

您可能会对这篇文章感兴趣,其中详细介绍了在使用 JavaScript SDK 版本 9 时定义与子集合相对应的

CollectionReference
的不同可能性。

© www.soinside.com 2019 - 2024. All rights reserved.