Ludvig Lund
Ludvig Lund

Reputation: 121

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

Upvotes: 11

Views: 18504

Answers (5)

user6684898
user6684898

Reputation:

I know this is a flutter firestore topic but I just want to share my answer.

I am using Vue and I am also doing a validation if the id is already taken on firestore.

This is my solution as of 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

Edit:

if you console.log(listSnapShot), the _document will be set to null if the id does not exist on firestore. See screenshot below

If it does not exist enter image description here

If ID already exists enter image description here

Upvotes: 0

Tonui Nicholus
Tonui Nicholus

Reputation: 395

To check if document exists in Firestore. Trick is to use .exists method

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

Upvotes: 6

AnEnigmaticBug
AnEnigmaticBug

Reputation: 959

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
}

Upvotes: 26

MobileMon
MobileMon

Reputation: 8651

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
   }

Upvotes: 9

mirkancal
mirkancal

Reputation: 5345

  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.

Upvotes: -1

Related Questions