How to check if festestore document for clouds exists when using real-time updates

It works:

db.collection('users').doc('id').get()
  .then((docSnapshot) => {
    if (docSnapshot.exists) {
      db.collection('users').doc('id')
        .onSnapshot((doc) => {
          // do stuff with the data
        });
    }
  });

... but it seems verbose. I tried doc.exists but that did not work. I just want to check if a document exists before subscribing to it in real time. This initial get looks like a mascot on db.

Is there a better way?

+3
source share
2 answers

Your initial approach is right, but it may be less difficult to assign a link to the document to such a variable:

const usersRef = db.collection('users').doc('id')

usersRef.get()
  .then((docSnapshot) => {
    if (docSnapshot.exists) {
      usersRef.onSnapshot((doc) => {
        // do stuff with the data
      });
    } else {
      usersRef.set({...}) // create the document
    }
});

Link: Get Document

+5
source
private void checkIfUserAlreadyExitsOrCreateOne(){
    docRef = db.collection(USERSCOLLECTION).document(emailid);
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            DocumentSnapshot documentSnapshot = task.getResult();
            if (documentSnapshot.exists()){
                Log.e(TAG, "Exits");

            }else{
                Log.e(TAG,"Not Exits");
            }
        }
    });
-1
source

Source: https://habr.com/ru/post/1689314/


All Articles