防止Firestore规则中的重复条目不起作用

时间:2019-01-17 12:52:44

标签: google-cloud-platform google-cloud-firestore firebase-security-rules

我正在尝试使用Google Firestore规则防止重复输入,但是它不起作用。我正在尝试的规则是:

service cloud.firestore {  
  // Prevent duplicate messages
  match /databases/{database}/documents {
    match /messages/{message} {
        allow read;
      allow write: if request.resource.data.m != resource.data.m;
    }
  }
}

根据我的阅读,这应该有效。

enter image description here

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您的规则if request.resource.data.m != resource.data.m说,只有与同一文档中的字段m 的当前值不同的情况下,才能写入字段m

无法检查整个集合中是否存在重复项,因为这将要求Cloud Firestore读取集合中的所有文档(不会缩放)。

当前实现唯一性约束的唯一方法是创建一个单独的集合,在其中使用m作为文档ID。由于集合中的文档ID在定义上是唯一的,因此您可以在其中强制执行以下规则:

match /unique_ms/{m} {
  allow create;
}

以上内容仅允许创建文档,不允许更新文档。这意味着一旦有人创建了具有特定值m的文档,任何人都无法覆盖它。

使用write规则的替代方法可能是:

allow write: if !exists(/databases/$(database)/documents/unique_ms/{m});

另请参阅: