【问题标题】:Reading firestore data with dynamic path使用动态路径读取 Firestore 数据
【发布时间】:2020-10-01 13:27:53
【问题描述】:

我已经更改了我的 Firestore 规则,以使所有者可以读取数据我的规则如下 -

service cloud.firestore {
match /databases/{database}/documents {
       match /users/defaultmenuItems {
          allow read: if request.auth != null;
          allow write: if false;
        }

        match /users/{userId} {
          allow read,update,write: if isOwner(userId); 
        } 

        function isOwner(userId) {
          return request.auth.uid == userId;
        }
    } 
}

我在使用动态路径读取值时遇到问题。我不知道为什么它不起作用?

firebaseFirestore.collection("users")
                .document(FirebaseAuth.getInstance().getCurrentUser().getUid() + "/"+dynamic_path)
                .get()
                .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        if (task.isSuccessful()) {
                            DocumentSnapshot documentSnapshot = task.getResult();
                            if (documentSnapshot.exists()) { 
                                Log.d(TAG, "Found Document");
                            } else {
                                getDeafaultItems(path);
                                Log.d(TAG, "Default");
                            }
                        } else {
                            Log.d(TAG, "Sorry ....");
                        }
                    }
                }); 
    }

【问题讨论】:

  • 我不明白你想用dynamic_path 完成什么。您的规则允许用户阅读具有自己 UID 的用户中的文档。这就是您的文档路径必须是什么。其他任何事情都会失败。请编辑问题以更详细地解释您希望在这里做什么。
  • 动态路径是嵌套文档/集合的名称。像 uid/vegitables 或 uid/fruits 或 uid/drinks 之类的东西。当我有默认的读写规则之前,它就可以工作。当我让它们成为特定用户时,它们停止工作。

标签: android firebase google-cloud-firestore firebase-security


【解决方案1】:

您的规则不允许对嵌套在用户文档下的子集合进行任何访问。您需要单独调用每个子集合并允许对其进行访问:

match /users/{userId} {
  allow read,update,write: if isOwner(userId); 
} 

match /users/{userId}/fruits {
  allow read,update,write: if isOwner(userId); 
} 

或者使用递归通配符匹配所有可能子集合中的所有可能文档:

match /users/{userId} {
  allow read,update,write: if isOwner(userId); 
} 

match /users/{userId}/{document=**} {
  allow read,update,write: if isOwner(userId); 
} 

我建议阅读documentation 中有关递归通配符的更多信息。

【讨论】:

  • 我收到此错误... DocumentSnapshot{key=users/QwnbAEE992Z1MAJkFOoJy4BUGzk1/fruits/berries, metadata=SnapshotMetadata{hasPendingWrites=false, isFromCache=false}, doc=null}
  • 修复了错误。别担心。 :) 感谢您的帮助
猜你喜欢
  • 2018-11-25
  • 2022-07-13
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多