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

JavaScript与Firestore:筛选未关注用户逻辑错误求助

解决方案

你的代码逻辑完全搞反了,问题出在这两点:

  1. 你在遍历following(已关注列表)做筛选,但正确逻辑应该是遍历从Firestore获取的所有用户,排除已关注的对象
  2. filter的回调返回了reduce生成的数组,数组在布尔判断中始终为真,导致filter保留了所有已关注项

修正后的代码如下:

function loadAllUsersDontFollow() {
  firestore()
    .collection("users")
    .where("id", "!=", user?.id)
    .get()
    .then((response) => {
      // 把Firestore文档转为用户数据数组
      const allUsers = response.docs.map(doc => doc.data());
      // 提取所有已关注用户的ID,用Set提升查找效率
      const followedUserIds = new Set(following.map(item => item.userId));
      // 过滤出不在已关注列表里的用户
      const unfollowedUsers = allUsers.filter(user => !followedUserIds.has(user.id));
      
      // 这里可以使用unfollowedUsers做后续处理,比如更新页面状态等
      console.log(unfollowedUsers);
    });
}

关键说明:

  • 用map把Firestore返回的文档对象转换为实际的用户数据,方便后续操作
  • 使用Set存储已关注用户ID,相比数组的includes(),Set.has()的查找性能更优,尤其是关注列表较大时
  • 直接对所有用户数组做过滤,排除掉已关注的ID,最终得到的就是你需要的未关注用户列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:41:01