防止Firestore规则中的重复条目不起作用 [英] Prevent duplicate entries in Firestore rules not working
问题描述
我正在尝试使用Google Firestore规则防止重复输入,但是它不起作用.我正在尝试的规则是:
I'm trying to prevent duplicate entries using Google Firestore rules, however it's not working. The rule I'm trying is:
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;
}
}
}
从我阅读的内容来看,这应该可行.
From what I read, this should work.
我在做什么错了?
推荐答案
您的规则if request.resource.data.m != resource.data.m
说,仅当字段m
与字段m
中的当前值不同时才能写入相同的文档.
Your rule if request.resource.data.m != resource.data.m
says that field m
can only be written if it's not the same as the current value of field m
in the same document.
无法按照安全规则检查整个集合中的重复项,因为这将要求Cloud Firestore读取集合中的所有文档(这在规模上会变得非常昂贵).
There is no way to check for duplicates in the entire collection in security rules, as that would require Cloud Firestore to read all documents in the collection (which would become very expensive at scale).
当前唯一实现唯一性约束的方法是创建一个单独的集合,在其中使用m
作为文档ID.由于集合中的文档ID在定义上是唯一的,因此您可以在其中强制执行以下规则:
The only way to currently implement a uniqueness constraint is by create a separate collection where you use m
as the document IDs. Since document IDs in a collection are by definition unique, you can enforce the rule there with:
match /unique_ms/{m} {
allow create;
}
以上内容仅允许创建文档,不允许更新文档.这意味着一旦有人创建了特定值m
的文档,任何人都无法覆盖它.
The above only allows creating a document, it does not allow updating it. This means that once someone created a document with a specific value of m
, nobody can overwrite it.
使用write
规则的替代方法可能是:
An alternative using the write
rule could be:
allow write: if !exists(/databases/$(database)/documents/unique_ms/{m});
另请参阅:
- Cloud Firestore: Enforcing Unique User Names
- firebase rule for unique property in firestore
这篇关于防止Firestore规则中的重复条目不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!