Flutter Firestore-检查文档ID是否已存在

时间:2019-05-06 20:39:56

标签: firebase dart flutter google-cloud-firestore

如果文档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”变量匹配。如果匹配,则不会创建该文档。如果不匹配,则应创建一个新文档

4 个答案:

答案 0 :(得分:1)

检查文件在Firestore中是否存在。使用技巧.exists

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

答案 1 :(得分:0)

  QuerySnapshot qs = await Firestore.instance.collection('posts').getDocuments();
  qs.documents.forEach((DocumentSnapshot snap) {
    snap.documentID == varuId;
  });

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

查询Firestore是异步的。您需要等待其结果,否则将获得Future,在此示例Future<QuerySnapshot>中。稍后,我从DocumentSnapshot(qs.documents)中获得了List<DocumentSnapshots>,对于每个快照,我都用varuId检查了它们的documentID

因此,这些步骤是查询Firestore,等待其结果,然后遍历结果。也许您可以在setState()之类的变量上调用isIdMatched,然后在您的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的文档引用。

答案 2 :(得分:0)

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

一个例子:

final snapShot = Firestore.instance
  .collection('posts')
  .document(docId)
  .get()

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

答案 3 :(得分:0)

在快照上使用exist方法:

final snapShot = await Firestore.instance.collection('posts').document("docID").get();

   if (snapShot.exists){
        //it exists
   }
   else{
        //not exists 
   }
相关问题