我尝试使用 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;
}
}
}
从我读到的来看,这应该有效。
我究竟做错了什么?
你的规则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});
另请参阅:
- Cloud Firestore:强制执行唯一的用户名 https://stackoverflow.com/questions/47405774/cloud-firestore-enforcing-unique-user-names
- firebase 中 firestore 中唯一属性的规则 https://stackoverflow.com/questions/51363730/firebase-rule-for-unique-property-in-firestore
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)