本文介绍了如何防止重复的用户Firebase的uname的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在活动中实施:



<$>我的聊天应用程序的用户名已成功添加到Firebase数据库。 p $ p> FirebaseDatabase firedb = FirebaseDatabase.getInstance();

在createUser方法中。

  private void createUser(String uname){
Map< String,Object> newUser = new HashMap< String,Object>();
newUser.put(uname,uname);
DatabaseReference dbref = firedb.getReference();
dbref.child(Users)。push()。setValue(newUser);

$ / code>

当用户点击一个按钮时,此方法正常工作,但我想使 uname 主键。如果alerady存在,我不想添加用户名。

数据库结构:
$ b

规则:

  {
rules:{
.read:true,
.write:true
}
}

最后,如何防止重复 uname

解决方案

顶级 / uname / 节点。您的数据将如下所示:

  {
用户:{
user1 :{
uname:value1,
},
user2:{
uname:value2,
},
user3:{
uname:value3,
},
},
uname:{
value1:user1 ,
value2:user2,
value3:user3,
}
}
$ b $现在你必须执行新的数据结构:

$ p $ {
rules:{
users:{
uname:{
.validate:!root.child('uname')。child(newData.val ())。exists()
},
}
}
}


I am adding username for my Chat App to Firebase Database successfully.

I implemented in activity:

FirebaseDatabase firedb = FirebaseDatabase.getInstance();

in createUser Method.

private void createUser(String uname){
    Map<String,Object> newUser = new HashMap<String, Object>();
    newUser.put("uname",uname);
    DatabaseReference dbref = firedb.getReference();
    dbref.child("Users").push().setValue(newUser);
}

When user click a button this method works. This method work correctly but I want to make uname primary key. I do not want to add a username if it is alerady exists.

Database Structure:

Rules:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Finally, how to prevent duplicated uname ?

解决方案

You have to add a top level /uname/ Node. Your data will be like this for example :

{
  "Users" : {
    "user1" : {
      "uname" : "value1",
    },
    "user2" : {
      "uname" : "value2",
    },
    "user3" : {
      "uname" : "value3",
    },
  },
  "uname" : {
    "value1": "user1",
    "value2": "user2",
    "value3": "user3",
  }
}

Now you have to Enforce New Data Structure:

{
  "rules": {
    "users": {
        "uname": { 
          ".validate": "!root.child('uname').child(newData.val()).exists()"
      },
    }
  }
}

这篇关于如何防止重复的用户Firebase的uname的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 16:36