您当前的规则规定,只有当该位置的数据具有带有当前用户的用户 ID 的子属性 'uid' 时,您才能写入该位置。
但是,如果该位置没有数据怎么办? data.child('uid').val() 将是 null,与当前用户 ID 不匹配。所以我们需要先检查数据是否存在,然后检查现有数据或新数据以确保用户ID匹配。
{
"rules": {
"Posts2":{
".read": true,
// if the post already exists, the editing user must have a matching user ID
// if the post doesn't exist, the stored user ID must match the current user
// allows creation
".write": "(data.exists() && data.child('uid').val() == auth.uid) || (!data.exists() && newData.child('uid').val() == auth.uid)"
}
}
}
虽然上述规则有效,但它们还允许用户将帖子的所有权转让给可能导致审核问题的任何其他用户。因此,无论帖子当前是否存在,我们都应确保任何新数据都具有匹配的用户 ID。
{
"rules": {
"Posts2":{
".read": true,
// if the post already exists, the editing user must have a matching user ID
// after the write completes, the stored user ID must match the current user
// allows creation
".write": "newData.child('uid').val() == auth.uid && (!data.exists() || data.child('uid').val() == auth.uid)"
}
}
}
上述规则允许创建帖子,但不能删除。如果这也需要,您现在可以使用:
{
"rules": {
"Posts2":{
".read": true,
// if the post already exists, the editing user must have a matching user ID
// if the post will exist, the editing user must have a matching user ID
// allows creation and deletion
".write": "(!data.exists() || data.child('uid').val() == auth.uid) && (!newData.exists() || newData.child('uid').val() == auth.uid)"
}
}
}
注意:与 JavaScript 不同,== and === are the same operator 在实时数据库安全规则中