Flutter firestore - Check if document ID already exists

前端 未结 4 1704
终归单人心
终归单人心 2020-12-02 01:48

I want to add data into the firestore database if the document ID doesn\'t already exists. What I\'ve tried so far:

// varuId == the ID that is set to the do         


        
相关标签:
4条回答
  • 2020-12-02 02:24
      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.

    Querying firestore is async. You need to await its result, otherwise you will get Future, in this example Future<QuerySnapshot>. Later on, I'm getting DocumentSnapshots from List<DocumentSnapshots> (qs.documents), and for each snapshot, I check their documentID with the varuId.

    So the steps are, querying the firestore, await its result, loop over the results. Maybe you can call setState() on a variable like isIdMatched, and then use that in your if-else statement.

    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. 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.

    0 讨论(0)
  • 2020-12-02 02:25

    To check if document exists in firestore. Trick use .exists method

    Firestore.instance.document('collection/$docId').get().then((onValue){
    onValue.exists ? //exists : //not exist ;
    });
    
    0 讨论(0)
  • 2020-12-02 02:28

    Use the exists method on the snapshot:

    final snapShot = await Firestore.instance.collection('posts').document("docID").get();
    
       if (snapShot.exists){
            //it exists
       }
       else{
            //not exists 
       }
    
    0 讨论(0)
  • 2020-12-02 02:35

    You can get() the document and use the exists property on the snapshot to check whether the document exists or not.

    An example:

    final snapShot = await Firestore.instance
      .collection('posts')
      .document(docId)
      .get()
    
    if (snapShot == null || !snapShot.exists) {
      // Document with id == docId doesn't exist.
    }
    
    0 讨论(0)
提交回复
热议问题