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

查看:26
本文介绍了检查 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. 密码

数据库结构

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

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 the existence of a 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);

您也可以使用查询来实现与此相同的事情:

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 you to 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天全站免登陆