Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user exists in Firestore

I'd like to create a users database in Cloud Firestore, with the email as the unique ID for each user. The users should be in a collection, and each user is a document.

This is how I check if the user exists in the login activity:

FirebaseFirestore db = FirebaseFirestore.getInstance();
                            final DocumentReference userRef = db.collection("users").document(email);
                            userRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                    if (task.isSuccessful()) {
                                        DocumentSnapshot document = task.getResult();

                                        Toast.makeText(LoginActivity.this, task.getResult().toString(),
                                                Toast.LENGTH_SHORT).show();

                                        if (document != null) {
                                            //The user exists...
                                        }


                                        else {
                                            //The user doesn't exist...
                                           }

                                        }
                                    }
                                    else
                                        connectionErrorActivity();

                                }
                            });

The database is empty, as you can see:

enter image description here

My problem is, that document is never null, even tough the database is empty. The toast shows that the string value of document is: COM.GOOGLE.FIREBASE.FIRESTORE.DOCUMENTSNAPSHOT@8ED6B96.

Is this the correct way to do this? What can I do to fix it?

like image 334
Tal Barda Avatar asked Dec 20 '25 03:12

Tal Barda


2 Answers

The result of this Task is a DocumentSnapshot. Whether or not the underlying document actually exists is available via the exists method.

If the document does exist you can call getData to get at the contents of it.

like image 82
Gil Gilbert Avatar answered Dec 22 '25 18:12

Gil Gilbert


Task result has a field named AdditionalUserInfo, you can find here isNewUser. it will return false if the user already exists.

  if (task.result?.additionalUserInfo!!.isNewUser){
         addNewUser()
    } else {
         updateUser()
  }
like image 35
Salman_Zach Avatar answered Dec 22 '25 18:12

Salman_Zach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!