Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. If it matches, the document won't be created. If it doesn't match, It should create a new document

like image 218
Ludvig Lund Avatar asked May 06 '19 20:05

Ludvig Lund


2 Answers

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.

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
}
like image 159
AnEnigmaticBug Avatar answered Sep 18 '22 12:09

AnEnigmaticBug


Use the exists method on the snapshot:

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

   if (snapShot.exists){
        // Document already exists
   }
   else{
        // Document doesn't exist
   }
like image 42
MobileMon Avatar answered Sep 17 '22 12:09

MobileMon