reactjs 在查询父集合云Firestore的基础上获取子集合

nkcskrwz  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(45)

我想在查询父集合后获得子集合中的所有文档,我想访问“关注”集合中的所有文档,因为您可以看到登录用户的屏幕截图
这是我的代码

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);
      });      
    };

字符串
这是我的数据库截图

polkgigr

polkgigr1#

您需要首先查询用户文档,以获取它的id,然后查询follow子集合,如下所示(未测试):

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

字符串
请注意,getDocs(q, "follow");不能工作,请参阅文档。
您可能会对这个article感兴趣,它详细介绍了在使用JavaScript SDK版本9时定义与子集合对应的CollectionReference的不同可能性。

  • 旁注:为什么不使用用户的uid作为其用户文档的文档ID?这将使事情变得更容易。*

相关问题