What's the best way to check if a Firestore re

2019-05-01 19:16发布

Given a given Firestore path what's the easiest and most elegant way to check if that record exists or not short of creating a document observable and subscribing to it?

3条回答
神经病院院长
2楼-- · 2019-05-01 19:37

Taking a look at this question it looks like .exists() can still be used just like with the standard Firebase database. Additionally, you can find some more people talking about this issue on github here

The documentation states

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);
    });
查看更多
混吃等死
3楼-- · 2019-05-01 19:39

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 )
  });
查看更多
男人必须洒脱
4楼-- · 2019-05-01 20:02

I Encountered Same Problem recently while using Firebase Firestore and i used 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 solution that if documents against our query was found or not

查看更多
登录 后发表回答