本文介绍了如何设置“主键”在Firebase中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我计划在留言板应用程序中创建自己的留言板的模式:

  { 
board:{
jane-board:{
//元信息,比如谁创建了这个板子
},
john-board:{
//元信息,比如谁创建了这个板子
},
...
},
jane-board:{
// data
},
john-board:{
// data
}
}

确保boards的规则不能包含两个 jane-board



我试过写规则,但是失败:

  {
rules:{
.read:true,
boards:{
写:真,
$ board_name:{
.validate:!newData.parent()。hasChild($ board _name)
}
}
}
}


解决方案

由于您使用板的名称作为存储它的关键,所以已经保证每个板名最多可以存在一次。

你试图完成什么并不完全清楚。但是,如果您试图阻止董事会的数据被覆盖,您可以通过以下方式来完成:

  {
rules:{
.read:true,
boards:{
$ board_name:{
.write: !data.parent()。hasChild($ board_name)
}
}
}
}
b
$ b

您的规则发生了变化:


  • 我删除了 .write:true from boards 。有了这个规则,每个人都可以阅读所有板,因为你。 c $ c>规则,因为它更像是阻止写入而不是验证结构
  • 我检查新电路板是否已经存在于 current 数据中。您正在检查 newData ,但是没有任何意义:新电路板将始终存在于新数据中。


This is the schema I plan to have for my message board app where users can create their own message boards:

{
    "boards" : {
        "jane-board" : {
            // meta information like who created this board
        },
        "john-board" : {
            // meta information like who created this board
        },
        ...
    },
    "jane-board" : {
        // data
    },
    "john-board" : {
        // data
    }
}  

What would be the rule to ensure that "boards" cannot contain two "jane-board"?

I tried writing a rule but it fails:

{
    "rules" : {
        ".read" : true,
        "boards" : {
            ".write" : true,
            "$board_name" : {
                ".validate" : "!newData.parent().hasChild($board_name)"
            }
        }
    }
}  
解决方案

Since you are using the board's name as the key to store it under, there is already a guarantee that each board name can exist at most once.

It is not entire clear what you're trying to accomplish. But if you are trying to prevent a board's data from being overwritten, you can accomplish that with:

{
    "rules" : {
        ".read" : true,
        "boards" : {
            "$board_name" : {
                ".write" : "!data.parent().hasChild($board_name)"
            }
        }
    }
}  

Changes for your rules:

  • I removed the ".write": true from boards. With that rule in place everyone can read all boards, since you cannot take permissions away on a lower level.
  • I changed the rule to a ".write" rule, since it feels more like preventing a write than validating structure
  • I check whether the new board already exists in the current data. You were checking in newData, but that doesn't make any sense: the new board will always exist in the new data.

这篇关于如何设置“主键”在Firebase中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 00:54