【问题标题】:Flutter firestore - Check if document ID already existsFlutter firestore - 检查文档ID是否已经存在
【发布时间】:2019-09-24 11:57:56
【问题描述】:

如果文档 ID 尚不存在,我想将数据添加到 firestore 数据库中。 到目前为止我尝试过的:

// varuId == the ID that is set to the document when created


var firestore = Firestore.instance;

if (firestore.collection("posts").document().documentID == varuId) {
                      return AlertDialog(
                        content: Text("Object already exist"),
                        actions: <Widget>[
                          FlatButton(
                            child: Text("OK"),
                            onPressed: () {}
                          )
                        ],
                      );
                    } else {
                      Navigator.of(context).pop();
                      //Adds data to the function creating the document
                      crudObj.addData({ 
                        'Vara': this.vara,
                        'Utgångsdatum': this.bastFore,
                      }, this.varuId).catchError((e) {
                        print(e);
                      });
                    }

目标是检查数据库中的所有文档 ID,并查看与“varuId”变量的任何匹配项。如果匹配,则不会创建文档。如果不匹配,它应该创建一个新文档

【问题讨论】:

  • Firestore 中没有简单的检查是否存在。您应该 get() 文档,然后查看结果是否包含实际文档。

标签: firebase dart flutter google-cloud-firestore


【解决方案1】:

您可以使用get()方法获取documentSnapshot,并使用快照上的exists属性来检查文档是否存在。

一个例子:

final snapShot = await FirebaseFirestore.instance
  .collection('posts')
  .doc(docId) // varuId in your case
  .get();

if (snapShot == null || !snapShot.exists) {
  // Document with id == varuId doesn't exist.

  // You can add data to Firebase Firestore here
}

【讨论】:

    【解决方案2】:

    在快照上使用 exists 方法:

    final snapShot = await FirebaseFirestore.instance.collection('posts').doc(varuId).get();
    
       if (snapShot.exists){
            // Document already exists
       }
       else{
            // Document doesn't exist
       }
    

    【讨论】:

    • 请说明您的答案将如何帮助解决问题,只是不要在没有上下文的情况下仅给出代码答案
    【解决方案3】:

    检查文档是否存在于 Firestore 中。诀窍是使用.exists 方法

    FirebaseFirestore.instance.doc('collection/$docId').get().then((onValue){
      onValue.exists ? // exists : // does not exist ;
    });
    

    【讨论】:

      【解决方案4】:
        QuerySnapshot qs = await Firestore.instance.collection('posts').getDocuments();
        qs.documents.forEach((DocumentSnapshot snap) {
          snap.documentID == varuId;
        });
      

      getDocuments() 获取此查询的文档,您需要使用它而不是 document(),它返回带有提供的路径的 DocumentReference。

      查询 firestore 是异步的。你需要等待它的结果,否则你会得到 Future,在这个例子中是 Future&lt;QuerySnapshot&gt;。稍后,我从List&lt;DocumentSnapshots&gt; (qs.documents) 获得DocumentSnapshots,对于每个快照,我使用varuId 检查他们的documentID

      因此,步骤是,查询 firestore,等待其结果,循环遍历结果。也许你可以在 isIdMatched 这样的变量上调用 setState(),然后在你的 if-else 语句中使用它。

      编辑:@Doug Stevenson 是对的,这种方法成本高、速度慢并且可能会耗尽电池,因为我们要获取所有文档来检查 documentId。也许你可以试试这个:

        DocumentReference qs =
            Firestore.instance.collection('posts').document(varuId);
        DocumentSnapshot snap = await qs.get();
        print(snap.data == null ? 'notexists' : 'we have this doc')
      

      我对数据进行空值检查的原因是,即使您在 document() 方法中放入随机字符串,它也会返回具有该 ID 的文档引用。

      【讨论】:

      • 问题是询问单个文档。我不建议获取整个集合只是为了找出一个具有已知 ID 的文档是否已经存在。这可能会非常缓慢且成本高昂。
      • 这不起作用检查下面的答案。检查一下,您会发现即使文档不存在,数据也不总是为空。
      猜你喜欢
      • 2020-11-27
      • 2014-10-06
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      相关资源
      最近更新 更多