避免创建额外的孩子Firebase [英] Avoid create extra childs Firebase

查看:51
本文介绍了避免创建额外的孩子Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是firebase中的新手,我想知道如何找出有关hasChildren()RuleDataSnapshot的问题以及如何创建数据的验证方法.

Im a new in firebase and I wish to know how to figure out a question regarding to hasChildren() RuleDataSnapshot and how validates the data will be created.

db的示例:

 {
  "visitors" : {

   "-KP4BiB4c-7BwHwdsfuK" : {
      "mail" : "aaa@mail.com",
      "name" : "aaa",
    }
    .....
}

规则:

{
    "rules": {
        "visitors": {
            ".read": "auth != null",
            ".write": "auth.uid != null",
                "$unique-id": {
                    ".read": "auth != null ",
                    ".write": "auth != null",
                    ".validate": "newData.hasChildren(['name','mail'])",
            }
        }

    }
}

据我所知,如果我想创建数据,则数据字段必须具有相同的名称才能通过规则验证.例如 :如果我更改每个名称"的名称",并尝试使用其子级创建一个新节点,则该规则在我所能理解的范围内有效.我想知道如果手动添加一个新字段来创建该怎么办?

As far I know if I want to create data, the data fields must have the same names to pass the rule validation. For example : If I change "name" per "names" and I try to create a new node with their childs the rule works as far I could understand. I wondering ¿ what happend if I add manually a new fields to create ?

例如:

//Add extra fields which are not actually present
 var data = {name : "xxx",mail:"xxx@mail.com",extra1:222,extra:333};
 firebase.database().ref('visitors/').push(data);

结果是:

  "visitors" : {
  "-KP4BiB4c-7BwHwdsfuK" : {
      "mail" : "aaa@mail.com",
      "name" : "juan",
     "extra1":222,
      "extra2":333
    }
}

所以我的问题是如何避免在每个节点上创建额外的子代?我以为规则是这样做的.

So my question is how to avoid create extra childs per node ? I supposed the rule did it.

谢谢.

推荐答案

您的验证规则表明,您的帖子必须具有至少个孩子,而不是个孩子.为确保不能添加其他子项,您必须在规则中添加以下内容:

Your validate rule says your post must have atleast those children and not only those children. To ensure no other children can be added you have to add the following to your rules:

{
  "rules": {
    "visitors": {
        ".read": "auth != null",
        ".write": "auth.uid != null",
        "$unique-id": {
            ".read": "auth != null ",
            ".write": "auth != null",
            //This line says the new data must have ATLEAST these children
            ".validate": "newData.hasChildren(['name','mail'])",   
            //You can add individual validation for name and mail here     
            "name": { ".validate": true },
            "mail": { ".validate": true },
            //This rule prevents validation of data with more child than defined in the 2 lines above (or more if you specify more children)
            "$other": { ".validate": false }
        }
    }
  }
}

此处再举一个例子.

这篇关于避免创建额外的孩子Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆