简体   繁体   English

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

[英]Flutter firestore - Check if document ID already exists

I want to add data into the firestore database if the document ID doesn't already exists.如果文档 ID 尚不存在,我想将数据添加到 firestore 数据库中。 What I've tried so far:到目前为止我已经尝试过:

// 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);
                      });
                    }

The goal is to check all the documents ID in the database and see in any matches with the "varuId" variable.目标是检查数据库中的所有文档 ID,并查看与“varuId”变量的任何匹配项。 If it matches, the document won't be created.如果匹配,则不会创建文档。 If it doesn't match, It should create a new document如果不匹配,它应该创建一个新文档

You can use the get() method to get the Snapshot of the document and use the exists property on the snapshot to check whether the document exists or not.您可以使用get()方法获取documentSnapshot并使用Snapshot上的exists属性来检查文档是否存在。

An example:一个例子:

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
}

Use the exists method on the snapshot:在快照上使用exists方法:

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

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

To check if document exists in Firestore.检查 Firestore 中是否存在文档。 Trick is to use .exists method技巧是使用.exists方法

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

I know this is a flutter firestore topic but I just want to share my answer.我知道这是一个 flutter firestore 主题,但我只想分享我的答案。

I am using Vue and I am also doing a validation if the id is already taken on firestore.我正在使用 Vue,如果 id 已经在 firestore 上,我也会进行验证。

This is my solution as of firebase version 9.8.2这是我从 firebase version 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();

The watchLink.value is the ID that you want to check watchLink.value是您要检查的 ID

Edit:编辑:

if you console.log(listSnapShot) , the _document will be set to null if the id does not exist on firestore.如果您使用console.log(listSnapShot) ,如果 id 在 firestore 上不存在,则_document将设置为 null。 See screenshot below请参阅下面的屏幕截图

If it does not exist如果不存在在此处输入图像描述

If ID already exists如果ID已经存在在此处输入图像描述

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

getDocuments() fetches the documents for this query, you need to use that instead of document() which returns a DocumentReference with the provided path. getDocuments() 获取此查询的文档,您需要使用它而不是 document() ,后者返回带有提供路径的 DocumentReference。

Querying firestore is async.查询 firestore 是异步的。 You need to await its result, otherwise you will get Future, in this example Future<QuerySnapshot> .你需要等待它的结果,否则你会得到 Future,在这个例子中Future<QuerySnapshot> Later on, I'm getting DocumentSnapshot s from List<DocumentSnapshots> (qs.documents), and for each snapshot, I check their documentID with the varuId.稍后,我从List<DocumentSnapshots> (qs.documents) 获取DocumentSnapshot ,对于每个快照,我使用 varuId 检查它们的documentID

So the steps are, querying the firestore, await its result, loop over the results.所以步骤是,查询firestore,等待它的结果,循环结果。 Maybe you can call setState() on a variable like isIdMatched , and then use that in your if-else statement.也许您可以对像isIdMatched这样的变量调用setState() ,然后在if-else语句中使用它。

Edit: @Doug Stevenson is right, this method is costly, slow and probably eat up the battery because we're fetching all the documents to check documentId.编辑:@Doug Stevenson 是对的,这种方法成本高、速度慢并且可能会耗尽电池,因为我们正在获取所有文档以检查 documentId。 Maybe you can try this:也许你可以试试这个:

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

The reason I'm doing null check on the data is, even if you put random strings inside document() method, it returns a document reference with that id.我对数据进行空检查的原因是,即使您将随机字符串放入 document() 方法中,它也会返回具有该 ID 的文档引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM