What is the best way to check if a Firestore entry exists if its path is known?

Given the given Firestore path, the easiest and most elegant way to check if this record exists or not create a document that can be watched and subscribed to?

+11
source share
3 answers

If you look at it , this question looks like it .existscan still be used in the same way as with the standard Firebase database. In addition, you can find a few more people who discuss this issue on github here

the documentation reads

NEW EXAMPLE

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

OLD EXAMPLE

var cityRef = db.collection('cities').doc('SF');

var getDoc = cityRef.get()
    .then(doc => {
        if (!doc.exists) {
            console.log('No such document!');
        } else {
            console.log('Document data:', doc.data());
        }
    })
    .catch(err => {
        console.log('Error getting document', err);
    });
+17
source

Check this:)

  var doc = firestore.collection('some_collection').doc('some_doc');
  doc.get().then((docData) => {
    if (docData.exists) {
      // document exists (online/offline)
    } else {
      // document does not exist (only on online)
    }
  }).catch((fail) => {
    // Either
    // 1. failed to read due to some reason such as permission denied ( online )
    // 2. failed because document does not exists on local storage ( offline )
  });
+2

I recently encountered the same problem when using Firebase Firestore and used the following approach to overcome it.

mDb.collection("Users").document(mAuth.getUid()).collection("tasks").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                if (task.getResult().isEmpty()){
                    Log.d("Test","Empty Data");
                }else{
                 //Documents Found . add your Business logic here
                }
            }
        }
    });

task.getResult (). isEmpty () provides a solution that, if the documents at our request were found or not

0
source

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


All Articles