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
You can
get()
the document and use theexists
property on the snapshot to check whether the document exists or not.An example:
To check if document exists in firestore. Trick use
.exists
methodgetDocuments() 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 gettingDocumentSnapshot
s fromList<DocumentSnapshots>
(qs.documents), and for each snapshot, I check theirdocumentID
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 likeisIdMatched
, and then use that in yourif-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:
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.
Use the exists method on the snapshot: