从集合中获取文档数据-具有Firestore安全规则

时间:2020-09-07 18:26:49

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

我在Firestore中创建规则时遇到问题。

这是我的示例: 集合“用户”->许多文档-> 并非每个文档都在内部,名为“食谱”的子集合。 如果存在子集合“配方”,则它具有包含一些数据的文档。 其中之一是带有布尔类型的“ 公共”。

我的问题: 如果“公开”的条件为真,我想从所有用户那里获得所有食谱。

规则中的Im堆栈:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read: if request.auth != null && request.auth.uid == userId;
      allow write: if request.auth != null && request.auth.uid == userId;
      match /recipes/{recipeId} {
            allow read: if resource.data.public == "true";
        }
    }
  }
}

enter image description here

它向我显示:错误:Simulator.rules第[9]行,第[21]列。空值错误。

在这种情况下,如何使用干净的javascript获取/调用此数据? 如果我刚得到一些脚本,例如firebase.firestore()或firebase.auth()。

2 个答案:

答案 0 :(得分:2)

对于他们正在寻找解决方案的人员。我找到一个! 让我解释一下:

  1. 我找到了https://firebase.google.com/docs/firestore/security/rules-query个有关查询规则的文档。
  2. 然后我决定使用firebase.firestore().collectionGroup('recipes').get().then(...)...
  3. 我的安全代码如下:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{path=**}/recipes/{document} {
      allow read: if resource.data.public == true;
    }
  }
}
  1. 我的JavaScript调用看起来像:
firebase.firestore().collectionGroup('recipes').where('public', '==', true).get().then(recipes => {
  recipes.forEach(doc => {
    console.log(doc.data());
  })
});
  1. 之后,我可以在console.log中看到错误:AILED_PRECONDITION: The query requires an index. You can create it here或熟悉链接的东西!
  2. 我单击了链接,然后接受了collectionGroup的索引设置。
  3. 您也可以在这里找到它: enter image description here

对不起,我的英语不好和Polskijęzyk很抱歉,但是我想我没错! 因此,它帮助我获得了在线公共食谱!

答案 1 :(得分:1)

您不能使用安全规则过滤结果。如果存在一个或更多违反该规则的文档,安全规则将阻止您的请求。您需要的是collection group queries。例如:

const querySnapshot = await db.collectionGroup('recipes').where('public', '==', true).get();
    querySnapshot.forEach((doc) => {
        console.log(doc.id, ' => ', doc.data());
});
相关问题