首页 > 解决方案 > 使用 React 查询过滤的 Firestore 数据 - 查询在规则游乐场中完美运行

问题描述

在 Firestore 中查询数据时,我正在努力解决权限错误。在规则游乐场中查询数据时,一切正常。一旦我在我的 React App 中尝试它,我就会收到以下错误:

index.js:1 快照侦听器中未捕获的错误:FirebaseError:缺少权限或权限不足。

在这里你可以看到我在 React 中的查询:

useEffect(() => {
    if (user.id && !user.therapist && user.therapistId) {
      const allowedIDs = getPatientTasksListState.map((item) => item.taskID);
      if (allowedIDs.length > 0) {
        const unsubscribe = db
          .collection("users")
          .doc(user.therapistId)
          .collection("tasks")
          .where("id", "in", allowedIDs)
          .onSnapshot((querySnapshot) => {
            const taskList: any[] = querySnapshot.docs.map((doc) => doc.data());
            setPatientTasksContentState(taskList);
          });
        return () => {
          unsubscribe();
        };
      }
    }
  }, [user, getPatientTasksListState, setPatientTasksContentState]);

这是我关于此查询的 Firestore 安全规则:

match /users/{userID}/tasks/{taskID} {
      allow read: if request.auth != null 
                  && userID == request.auth.uid
                  || (request.auth != null && (taskID in get(/databases/$(database)/documents/users/$(userID)/patients/$(request.auth.uid)).data.taskIDs))
      allow write: if userID == request.auth.uid
    }

这是firestore中有关此问题的一些测试数据的屏幕截图:

Firestore 数据库数据的屏幕截图

标签: reactjsfirebasegoogle-cloud-firestore

解决方案


在安全规则中将 taskID 更改为 resource.data.id 为我解决了这个问题:

match /users/{userID}/tasks/{taskID} {
  allow read: if request.auth != null 
              && userID == request.auth.uid
              || (request.auth != null && (resource.data.id in get(/databases/$(database)/documents/users/$(userID)/patients/$(request.auth.uid)).data.taskIDs))
  allow write: if userID == request.auth.uid
}

推荐阅读