You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cloud Firestore:查询父集合后获取登录用户的follow子集合文档

获取Cloud Firestore中当前用户的follow子集合数据

你的代码存在两个关键问题:

  • getDocs(q, "follow")写法错误,getDocs仅接受查询对象作为参数,第二个参数无意义
  • 代码仅获取了users集合中匹配的用户文档,没有进一步读取该文档下的follow子集合

下面是修正后的完整代码,分步骤实现需求:

const getFollowingUsers = async () => {
  // 第一步:查询users集合中当前登录用户的文档(通过uid匹配)
  const usersQuery = query(collection(db, "users"), where("uid", "==", user.uid));
  const usersSnapshot = await getDocs(usersQuery);

  // 判断是否找到用户文档
  if (usersSnapshot.empty) {
    console.log("未找到当前用户对应的文档");
    setFollowingUsers([]);
    return;
  }

  // 第二步:获取匹配到的用户文档(uid唯一,仅需取第一个)
  const userDoc = usersSnapshot.docs[0];
  // 第三步:获取该用户文档下的follow子集合引用
  const followCollection = collection(userDoc.ref, "follow");
  // 第四步:读取follow子集合的所有文档
  const followSnapshot = await getDocs(followCollection);

  // 第五步:整理子集合数据并更新状态
  const followData = followSnapshot.docs.map(doc => ({
    id: doc.id,
    ...doc.data()
  }));
  setFollowingUsers(followData);
};

优化建议(如果用户文档ID与uid一致)

如果你的users集合中文档ID直接使用用户的uid(而非自动生成ID),可以跳过查询步骤,直接构造文档引用,提升性能:

const getFollowingUsers = async () => {
  // 直接通过uid构造用户文档引用
  const userDocRef = doc(db, "users", user.uid);
  const userDocSnapshot = await getDoc(userDocRef);

  if (!userDocSnapshot.exists()) {
    console.log("未找到当前用户对应的文档");
    setFollowingUsers([]);
    return;
  }

  // 后续读取follow子集合的逻辑同上
  const followCollection = collection(userDocRef, "follow");
  const followSnapshot = await getDocs(followCollection);
  
  const followData = followSnapshot.docs.map(doc => ({
    id: doc.id,
    ...doc.data()
  }));
  setFollowingUsers(followData);
};

内容的提问来源于stack exchange,提问作者user1450966

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 00:25:59