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

Lud*_*und 8 dart firebase 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);
                      });
                    }
Run Code Online (Sandbox Code Playgroud)

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

AnE*_*Bug 20

您可以使用该get()方法来获得Snapshotdocument,使用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
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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

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


Mob*_*Mon 6

在快照上使用exists方法:

final snapShot = await FirebaseFirestore.instance.collection('posts').doc(varuId).get();

   if (snapShot.exists){
        // Document already exists
   }
   else{
        // Document doesn't exist
   }
Run Code Online (Sandbox Code Playgroud)

  • 请解释您的答案将如何帮助解决问题,并且不要在没有上下文的情况下仅给出代码答案 (2认同)

mir*_*cal -1

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

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

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

所以步骤是,查询 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')
Run Code Online (Sandbox Code Playgroud)

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

  • 问题是询问单个文档。我不建议仅仅为了查明具有已知 ID 的文档是否已存在而获取整个集合。这可能非常缓慢且成本高昂。 (5认同)