首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Firestore rules if..else

Firestore rules if..else
EN

Stack Overflow用户
提问于 2018-06-06 08:21:56
回答 3查看 3.3K关注 0票数 10

我刚刚开始了解Firestore规则,并且我的头脑正在迅速扩大。

我正在尝试解决如何将一条规则应用于一个集合,而将另一条规则应用于所有其他集合及其子集合。

因此,我从Firestore似乎附带的默认规则开始:

代码语言:javascript
复制
service cloud.firestore {
  match /databases/{database}/documents {

    match /{document=**} {
      allow read, write;
    }
  }
}

这将允许对所有集合及其文档的读写访问。

但是假设我想对一个集合中的文档应用一个规则,并为所有其他集合保留默认规则。以下内容将不起作用:

代码语言:javascript
复制
service cloud.firestore {
  match /databases/{database}/documents {

      match /suppliers/{supplier} {
        allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
}

  match /{document=**} {
    allow read, write;
}


 }
}

因为第二条规则将覆盖第一条规则。

有没有办法做我想做的事?

EN

回答 3

Stack Overflow用户

发布于 2019-05-31 15:06:29

我知道您希望将规则应用于一个集合中的文档,并为所有其他集合保留默认规则。有一种方法可以做你想做的事情,但你不会喜欢它的。

您必须显式指定所有其他集合的默认规则。

这是一个示例。

代码语言:javascript
复制
service cloud.firestore {
  match /databases/{database}/documents {

    //Rule for Suppliers collection
    match /suppliers/{supplier} {
        allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
    }

    //Rule for Changelog collection allowing complete access
    match /Changelog/{id} {
        allow read: if true;
        allow write: if true;
    }

    //Rule for Vendors collection allowing complete access
    match /Vendors/{id} {
        allow read: if true;
        allow write: if true;
    }

  }
}

注意: Firestore规则不支持if else语句。但您可以使用AND和OR条件作为变通方法来模拟相同的情况。

票数 3
EN

Stack Overflow用户

发布于 2020-02-26 03:51:34

这里的基本问题是,当您有多个match语句时,如果其中任何一个match语句返回true,则允许读/写。可以在这里的文档中找到这方面的参考资料...

https://firebase.google.com/docs/firestore/security/rules-structure#overlapping_match_statements

要实现您想要执行的操作,您需要从规则中排除与所有文档匹配的特定路径。这可以通过添加检查来查看路径的第一部分是否与您排除的路径不匹配。

代码语言:javascript
复制
service cloud.firestore {
  match /databases/{database}/documents {

    match /suppliers/{supplier} {
      allow create: if !exists(/databases/$(database)/documents/suppliers/ABNs/1260)
    }

    // Use this instead of the original /{document=**} check
    match /{collectionName}/{document=**} {
      allow read, write: if collectionName != 'suppliers';
    }
  }
}
票数 1
EN

Stack Overflow用户

发布于 2018-06-06 10:38:17

代码语言:javascript
复制
service cloud.firestore {
  match /databases/{database}/documents {

    match /suppliers/{supplier} {
      allow create: if isValidSupplier()
    }

    function isValidSupplier() {
        return resource.data.supplierABNs == '1260'
    }

    match /{document=**} {
      allow read, write;
    }
  }
}

resource.data包含现有文档中的值。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50710650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档