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

10

如果文档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() 文档,然后查看结果是否包含实际文档。 - Doug Stevenson
5个回答

25
您可以使用get()方法获取document的快照,并在快照上使用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
}

9

在快照上使用exists方法:

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

   if (snapShot.exists){
        // Document already exists
   }
   else{
        // Document doesn't exist
   }

2
请解释一下你的答案如何帮助解决问题,不要只给出没有上下文的代码答案。 - Arun Vinoth-Precog Tech - MVP

6

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

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

0

我知道这是一个Flutter Firestore的话题,但我只是想分享我的答案。

我正在使用Vue,并且如果Firestore中的ID已经被占用,我也在进行验证。

截至Firebase 版本9.8.2,这是我的解决方案。

    const load = async() => {
        try {
            const listRef = doc(db, 'list', watchLink.value);
            let listSnapShot = await getDoc(listRef);

            if(listSnapShot._document == null) {
                await setDoc(doc(db, 'list', watchLink.value), {
                    listName: NameofTheList.value
                });

                throw Error('New list added');
            }
            else {
                
                throw Error('List already Exist');
            }
            
        } catch (error) {
            console.log(error.message);
        }
    }
  load();

watchLink.value 是您要检查的 ID

编辑:

如果您 console.log(listSnapShot),且 ID 在 firestore 上不存在,则 _document 将设置为 null。请参见下面的屏幕截图

如果不存在 enter image description here

如果 ID 已经存在 enter image description here


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

getDocuments() 函数获取此查询的文档,您需要使用它来代替返回提供路径的 DocumentReference 的 document() 函数。

Firestore 查询是异步的。您需要等待其结果,否则您将得到 Future,在本例中为 Future<QuerySnapshot>。稍后,我从 List<DocumentSnapshots> (qs.documents) 中获取 DocumentSnapshot,并对每个快照检查它们的 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')

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

5
这个问题是关于一个单独的文件的。我不建议检索整个集合,只为了查找已知ID的一个文档是否存在。这可能会非常缓慢和昂贵。 - Doug Stevenson
这个不会起作用,请查看下面的答案。检查后你会意识到,即使文档不存在,数据也不总是为空。 - Tonui Nicholus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接