且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Firestore查询-检查用户名是否已存在

更新时间:2023-11-28 14:09:52

要解决此问题,请使用以下代码行:

To solve this, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference allUsersRef = rootRef.collection("all_users");
Query userNameQuery = allUsersRef.whereEqualTo("username", "userNameToCompare");
userNameQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                if (document.exists()) {
                    String userName = document.getString("username");
                    Log.d(TAG, "username already exists");
                } else {
                    Log.d(TAG, "username does not exists");
                }
            }
        } else {
            Log.d("TAG", "Error getting documents: ", task.getException());
        }
    }
});

其中userNameToCompare的类型为String,并且是您要与之进行比较的用户的用户名.

In which userNameToCompare is of type String and is the user name of the user with which you want to make the comparison.