Firebase数据库规则:如何防止某个child被删除(a.k.a NOT NULL)?
Firebase database rules: How to prevent a certain child from being deleted (a.k.a NOT NULL)?
我正在尝试在 firebase 中定义一个模式,以防止某些 child 属性为空(例如 SQL 中的 NOT NULL 约束)。
架构应如下所示:
Property | allow null | type
---------+------------+--------
name | false | string
phone | false | string
alias | true | string
birthday | true | number (timestamp)
此外,只有用户自己应该能够读取和写入自己的联系人。
目前数据库中有一些虚拟数据:
{
"contacts" : {
"user1" : {
"contact1" : {
"alias" : "Bobby",
"name" : "Bob",
"phone" : "12312324"
}
}
}
}
我想出的解决方案是这样的:
{
"rules": {
"contacts": {
"$user": {
"$contact": {
".read": "auth.uid == $user",
".write": "auth.uid == $user && newData.hasChildren(['name', 'phone'])",
"name": {
".validate": "newData.isString()"
},
"phone": {
".validate": "newData.isString()"
},
"alias": {
".validate": "newData.isString()"
},
"birthday": {
".validate": "newData.isNumber()"
},
"$other": {
".validate": "false"
}
}
}
}
}
}
这种方法的问题是每次我想修补某个值(例如别名)时,由于 newData.hasChildren(['name', 'phone']
规则。
虽然我可以访问我的应用程序中的整个 object,但这是一个令人讨厌的不便。
有没有更好的方法来解决这个问题?
The problem with this approach is that every time that I want to patch a certain value (for example the alias), I have to provide the not null properties (that aren't changed) due to the newData.hasChildren(['name', 'phone']
rule.
你好像误解了规则中newData
的意思。来自 reference documentation of newData
:
A RuleDataSnapshot
corresponding to the data that will result if the write is allowed.
因此,如果您只将一个 属性 写入已包含所有属性的位置,则 newData
变量将包含所有属性:未指定的现有值,以及新的您正在写的 属性 的值。
我正在尝试在 firebase 中定义一个模式,以防止某些 child 属性为空(例如 SQL 中的 NOT NULL 约束)。
架构应如下所示:
Property | allow null | type
---------+------------+--------
name | false | string
phone | false | string
alias | true | string
birthday | true | number (timestamp)
此外,只有用户自己应该能够读取和写入自己的联系人。
目前数据库中有一些虚拟数据:
{
"contacts" : {
"user1" : {
"contact1" : {
"alias" : "Bobby",
"name" : "Bob",
"phone" : "12312324"
}
}
}
}
我想出的解决方案是这样的:
{
"rules": {
"contacts": {
"$user": {
"$contact": {
".read": "auth.uid == $user",
".write": "auth.uid == $user && newData.hasChildren(['name', 'phone'])",
"name": {
".validate": "newData.isString()"
},
"phone": {
".validate": "newData.isString()"
},
"alias": {
".validate": "newData.isString()"
},
"birthday": {
".validate": "newData.isNumber()"
},
"$other": {
".validate": "false"
}
}
}
}
}
}
这种方法的问题是每次我想修补某个值(例如别名)时,由于 newData.hasChildren(['name', 'phone']
规则。
虽然我可以访问我的应用程序中的整个 object,但这是一个令人讨厌的不便。
有没有更好的方法来解决这个问题?
The problem with this approach is that every time that I want to patch a certain value (for example the alias), I have to provide the not null properties (that aren't changed) due to the
newData.hasChildren(['name', 'phone']
rule.
你好像误解了规则中newData
的意思。来自 reference documentation of newData
:
A
RuleDataSnapshot
corresponding to the data that will result if the write is allowed.
因此,如果您只将一个 属性 写入已包含所有属性的位置,则 newData
变量将包含所有属性:未指定的现有值,以及新的您正在写的 属性 的值。