【问题标题】:flutter / dart How can check if a document exists in firestore?颤振/飞镖如何检查文件是否存在于firestore中?
【发布时间】:2020-01-12 14:04:53
【问题描述】:

我尝试使用布尔值查询 cloudfirestore 上是否存在文档。不幸的是,我的代码不起作用

我尝试了以下,但布尔值没有改变。

getok() {
  bool ok;
  Firestore.instance.document('collection/$name').get().then((onexist){
      onexist.exists ? ok = true : ok = false;
    }
  ); 
  if (ok = true) {
    print('exist');
  } else {
    print('Error');
  }
}

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    虽然我是 IDS,但你可以尝试这样做

    //Declare as global variable
    
    bool exist;
    
    static Future<bool> checkExist(String docID) async {       
        try {
            await Firestore.instance.document("users/$docID").get().then((doc) {
                exist = doc.exists;
            });
            return exist;
        } catch (e) {
            // If any error
            return false;
        }
    }
    

    【讨论】:

      【解决方案2】:

      Async / Await 函数检查 Firestore 中是否存在文档(使用 Flutter / Dart)

      一个简单的 async / await 函数,您可以调用它来检查文档是否存在。返回真或假。

      bool docExists = await checkIfDocExists('document_id');
      print("Document exists in Firestore? " + docExists.toString());
      
      /// Check If Document Exists
      Future<bool> checkIfDocExists(String docId) async {
        try {
          // Get reference to Firestore collection
          var collectionRef = Firestore.instance.collection('collectionName');
      
          var doc = await collectionRef.document(docId).get();
          return doc.exists;
        } catch (e) {
          throw e;
        }
      }
      

      【讨论】:

      • 发现当文档ID不存在时不返回false,会报错!
      • 刚刚检查过,如果文档不存在则返回 false
      • 捕捉到错误时会发生什么,bool会返回错误还是false?
      • @Dalon 会抛出错误。 doc.exists 将返回 true 或 false,catch 处理与 Firestore 通信的错误。如果您希望程序像错误一样继续运行(因此始终在 catch 中返回 false),或者您想以其他方式处理错误(例如显示自定义错误消息),这取决于您。跨度>
      【解决方案3】:

      你可以试试这个对我有用

      Future getDoc() async{
         var a = await Firestore.instance.collection('collection').document($name).get();
         if(a.exists){
           print('Exists');
           return a;
         }
         if(!a.exists){
           print('Not exists');
           return null;
         }
      
        }
      

      【讨论】:

        【解决方案4】:

        首先你需要等待答案,其次你总是从数据库中得到答案。这意味着onexists 确实一直存在。

        您可以使用 .documentID 检查文档是否存在。类似的东西:

        try {
          var res = await Firestore.instance.document('collection/$name').get();
          print(res.documentID ? 'exists' : 'does not exist');
        
        } catch (err) {
          print(err);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-03
          • 2020-08-12
          • 2020-11-05
          • 2022-07-20
          • 1970-01-01
          • 2020-11-28
          • 2018-09-10
          相关资源
          最近更新 更多