Cloud Firestore规定正确的语法
我需要为Cloud Firestore编写规则.
I need to write rules for Cloud Firestore.
我希望我的规则允许在集合中创建新文档:
I want my rules to allow the creation of a new document in a collection:
newDoc(field1="value-1", field2="value-2", field3="other-miscellaneous-values")
仅当集合中不存在具有以下条件的其他文档时:
only if no other document already exists in the collection with:
(field1 == "value-1") and (field2 == "value-2")
尽管这不是很复杂,但似乎仍然太复杂了,以至于找不到我在网上搜索的任何教程中的例子.
Though this is not very complicated, it seems still too complex to be found as an example in any tutorial that I found searching the net.
此外,如果用户愿意,可以*列出和阅读馆藏中的所有文档.
Beside, the user should be free to list and read all the documents in the collection if she/he wishes.
这是我尝试过的方法,但是不起作用:
Here is what I have tried, but it does not work:
service cloud.firestore {
function alreadyExists(document) {
return exists((resource.data.field1==request.resource.data.field1)&&
(resource.data.field2==request.resource.data.field2))
}
match /databases/{database}/documents {
match /My_Collection/{anything=**} {
allow read;
allow write: if !(alreadyExists(request.resource.data));
}
}
}
我希望有人能给我一些建议,以使其正常工作.
I hope someone can give me some advice to get it working.
安全规则只能检查特定路径下的文档是否存在(使用exists
).无法检查规则中是否存在具有特定值的文档.
Security rules can only check if a document at a certain path exists (with exists
). There is no way to check if a document with a certain value exists in rules.
针对您的用例,我的典型解决方案是将要唯一的字段组合用作文档的ID.根据定义,由于文档ID在给定的集合中是唯一的,因此可以确保您的键组合在同一集合中是唯一的.
My typical solution for your use-case would be to use the combination of fields that you want to be unique as the ID of the document. Since document IDs are by definition unique in a given collection, that ensures that your combination of keys is unique in that same collection.
如果您已经拥有无法更改的ID策略,请考虑添加一个包含唯一组合的辅助集合,如我的答案所示:
If you already have an ID strategy that you can't change, consider adding a secondary collection to contain the unique combinations, as shown in my answer here: Prevent duplicate entries in Firestore rules not working.