【问题标题】:What's the best way to check if a Firestore record exists if its path is known?如果路径已知,检查 Firestore 记录是否存在的最佳方法是什么?
【发布时间】:2018-04-28 17:20:19
【问题描述】:

给定一个给定的 Firestore 路径,检查该记录是否存在或不缺少创建可观察文档并订阅它的最简单和最优雅的方法是什么?

【问题讨论】:

    标签: firebase angularfire2 google-cloud-firestore


    【解决方案1】:

    看看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 引用的位置没有文档,则生成的文档将为空,调用 exists 将返回 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);
        });
    

    【讨论】:

    • 谢谢!我认为您的回答有一些遗漏吗?
    • 什么意思?是否有我遗漏的用例或其他什么?
    • 我的意思是代码不会像你写的那样加起来。粘贴时可能有些东西丢失了。
    • get 函数是否已弃用?
    • 这个答案不再有效。当我使用它时,get 函数返回一个 observable 而不是一个 promise。您需要添加 docRef.ref.get
    【解决方案2】:

    检查这个:)

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

    【讨论】:

      【解决方案3】:

      如果模型包含太多字段,最好在CollectionReference::get() 结果上应用字段掩码(让我们保存更多谷歌云流量计划,\o/)。因此,最好选择使用CollectionReference::select() + CollectionReference::where() 来仅选择我们想从 Firestore 中获取的内容。

      假设我们具有与 firestore cities example 相同的集合架构,但在我们的文档中具有与 doc::id 相同的值的 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,而不是下载整个文档来检查它是否存在。

      【讨论】:

      【解决方案4】:

      我最近在使用 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
                      }
                  }
              }
          });
      

      task.getResult().isEmpty() 提供解决方案,判断是否找到了针对我们查询的文档

      【讨论】:

        【解决方案5】:

        根据您使用的库,它可能是可观察的而不是承诺。只有promise 会有'then' 语句。您可以使用 'doc' 方法代替 collection.doc 方法,或 toPromise() 等。以下是 doc 方法的示例:

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

        希望这会有所帮助...

        【讨论】:

          【解决方案6】:

          如果出于某种原因你想在 Angular 中使用 observable 和 rxjs 而不是 Promise:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-03-31
            • 2011-05-25
            • 2012-08-29
            • 2011-03-20
            • 2011-12-25
            • 1970-01-01
            • 2014-01-05
            • 2020-11-08
            相关资源
            最近更新 更多