检查Firebase数据库中是否存在特定值 [英] Checking if a particular value exists in the Firebase database

查看:84
本文介绍了检查Firebase数据库中是否存在特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase实时数据库制作一个Android应用程序.当新用户在我的应用上注册时,该用户的数据将保存在Firebase数据库中.

I am making an Android application using Firebase realtime database. When a new user registers on my app, that user's data is saved in the Firebase database.

用户必须提供以下详细信息才能注册:

A user has to provide the following details to register:

  1. 全名
  2. 电子邮件
  3. 用户名
  4. 密码

数据库结构

每当一个新用户尝试注册时,我都必须确保每个用户的用户名都是唯一的,因此我要检查数据库中用户输入的username是否已经存在于数据库中.

Whenever a new user tries to register, I have to make sure that each user's username is unique so I check the database if the username entered by the user already exists in the database or not.

为此,我编写了以下方法:

To do this, I wrote the following method:

private boolean usernameExists(String username) {
     DatabaseReference fdbRefer = FirebaseDatabase.getInstance().getReference("Users/"+username);
     return (fdbRefer != null);
}

此方法背后的逻辑是,如果getReference方法找不到对指定路径的引用,它将返回null,这样我就可以返回fdbRefer是否为null.如果fdbRefernull,则意味着username在数据库中不存在.

My logic behind this method is that if getReference method cannot find reference to the specified path, it will return null so that I can return whether fdbRefer is null or not. If fdbRefer is null, then it means that username doesn't exist in the database.

此方法的问题在于,无论输入的username是否存在于数据库中,它总是返回true.这使我相信fdbRefer从来都不是null.

Problem with this method is that it always returns true whether the entered username exists in the database or not. Which led me to believe that fdbRefer is never null.

这使我想起了问题...

This brings me to my question...

getReference方法在firebase数据库中找不到指定的路径时返回什么?检查username在数据库中是否已存在的正确方法是什么?

What does getReference method return when it can't find the specified path in the firebase database and what's the correct way to check if the username already exists in the database or not?

推荐答案

要检查用户是否存在,请使用以下代码:

To check a existence of user, please use the below code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = rootRef.child("Users").child("Nick123");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(!dataSnapshot.exists()) {
            //create new user
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
userNameRef.addListenerForSingleValueEvent(eventListener);

您还可以使用Query来实现类似的目的:

You can also use a Query to achieve the same thing like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users").orderByChild("userName").equalTo("Nick123");
query.addValueEventListener(/* ... */);

这是另一种遍历整个Users节点的方法,而不仅仅是使用对单个用户的直接引用.当您将uid而不是用户名用作用户的唯一标识符时,更可能使用此选项(如您现在所做的那样).因此,如果您的数据库结构可能类似于以下内容:

This is another approach which is looping through the entire Users node but is not just using a direct reference to a single user. This option is more likely to be used when you are using as a unique identifier beteeen users the uid instead of the user name (as you do right now). So if your database structure might looks similar to this:

Firebase-root
   |
   --- Users
        |
        --- uid
             |
             --- userName: "Test User"
             |
             --- emailAddress: "user@email.com"

第二种解决方案是推荐的解决方案.

The second solution is the recommended one.

还有另一种解决方案,涉及到您创建另一个名为userNames的节点,在该节点中,您只能保存唯一的用户名.也请在下面找到相应的安全规则:

There is also another solution which involves youto create another node named userNames, in which you can hold only the unique user names. Please also find below the corresponding security rules:

"Users": {
  "$uid": {
    ".write": "auth !== null && auth.uid === $uid",
    ".read": "auth !== null && auth.provider === 'password'",
    "userName": {
      ".validate": "
        !root.child('userNames').child(newData.val()).exists() ||
        root.child('userNames').child(newData.val()).val() == $uid"
    }
  }
}

但是由于在这种情况下,您的用户名已经是该节点的名称,所以我建议您继续使用第一个.

But since in this case, your user name is already the name of the node, I recommend you go ahead with the first one.

这篇关于检查Firebase数据库中是否存在特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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