代码之家  ›  专栏  ›  技术社区  ›  David Haddad

如果Firestore记录的路径已知,那么检查其是否存在的最佳方法是什么?

  •  31
  • David Haddad  · 技术社区  · 8 年前

    6 回复  |  直到 8 年前
        1
  •  53
  •   DoesData    5 年前

    看看 this question 看起来像 .exists 仍然可以像使用标准Firebase数据库一样使用。此外,你可以在github上找到更多的人在谈论这个问题 here

    这个 documentation

    新示例

    var docRef = db.collection("cities").doc("SF");
    
    docRef.get().then((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((error) => {
        console.log("Error getting document:", error);
    });
    

    const cityRef = db.collection('cities').doc('SF');
    const doc = await cityRef.get();
        
    if (!doc.exists) {
        console.log('No such document!');
    } else {
        console.log('Document data:', doc.data());
    }
    

    注意:如果docRef引用的位置没有文档,则生成的文档将为空,对其进行调用将返回false。

    旧示例2

    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);
        });
    
        2
  •  8
  •   ch4k4uw    5 年前

    如果模型包含太多字段,最好在 CollectionReference::get() 结果(让我们保存更多谷歌云流量计划,\o/)。所以选择使用 CollectionReference::select() + CollectionReference::where() 只选择我们想从firestore获得的内容。

    假设我们的集合模式与firestore相同 cities example ,但带有 id 字段的值相同 doc::id . 然后你可以做:

    var docRef = db.collection("cities").select("id").where("id", "==", "SF");
    
    docRef.get().then(function(doc) {
        if (!doc.empty) {
            console.log("Document data:", doc[0].data());
        } else {
            console.log("No such document!");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
    

    现在我们只下载 city::id 而不是下载整个文档只是为了检查它是否存在。

        3
  •  5
  •   Rifat Haque Amit    8 年前

      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
  •  0
  •   Muhammad Usman    7 年前

    我最近在使用Firebase Firestore时遇到了同样的问题,我使用了以下方法来克服它。

    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
                    }
                }
            }
        });
    

    任务getResult()。isEmpty()提供了一种解决方案,可以解决是否找到了针对我们的查询的文档的问题

        5
  •  0
  •   Jonathan    6 年前

    let userRef = this.afs.firestore.doc(`users/${uid}`)
    .get()
    .then((doc) => {
      if (!doc.exists) {
    
      } else {
    
      }
    });
    
    })
    

    希望这有帮助。。。

        6
  •  0
  •   Jonathan    5 年前

    如果出于任何原因,你想在角度上使用可观察和rxjs,而不是承诺:

    this.afs.doc('cities', "SF")
    .valueChanges()
    .pipe(
      take(1),
      tap((doc: any) => {
      if (doc) {
        console.log("exists");
        return;
      }
      console.log("nope")
    }));