![](/img/trans.png)
[英]How to check whether the field exists in Firebase, if it exists then print its value, if it does not exist, then add it with an empty value in Flutter
[英]How can I check whether a document exists based on an optional field?
我正在编写一些 Firestore 规则以允许用户创建帖子并互相回复。 我有一些规则来检查帖子是否有效。
function isPost(data) {
return data.keys().hasOnly(["title", "text", "parent")
&& data.title is string
&& data.get("text", "") is string
}
如何添加一个可选的“replyTo”字段,该字段仅在它引用数据库中的现有文档(帖子)时才有效?
我试过这个
function isPost(data) {
return data.keys().hasOnly(["title", "text"])
&& data.title is string
&& data.get("text", "") is string
+ && exists(/databases/$(database)/documents/posts/$(data.get("replyTo", "")))
}
但它不会返回对有效文档的引用,因此会失败。
编辑:基于@Dharmaraj 的回答的工作解决方案:
function isPost(data) {
return data.keys().hasOnly(["title", "text"])
&& data.title is string
&& data.get("text", "") is string
&& !('replyTo' in data) || exists(/databases/$(database)/documents/$(data.replyTo))
}
如果replyTo
字段是一个引用,那么它的值将是posts/postId
,因此您不需要路径中的集合名称:
// remove /posts from this
exists(/databases/$(database)/documents/$(data.replyTo))
如果replyTo
字段丢失或将确保引用的文档存在,则以下规则将通过:
allow read: if !('replyTo' in data) || exists(/databases/$(database)/documents/$(data.replyTo))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.