I would like to know if specific document exists, update that document and if not create that document is possible in Firestore or not.
For example, user entered some tag with post, then look like thisFirestore.instance.collection('tags').document(tag here).updateData()
.
Is there any way if that document doesn't exist, then create method or do I have to check if exists before writing it?
Collections and documents are created implicitly in Cloud Firestore. Simply assign data to a document within a collection. If either the collection or document does not exist, Cloud Firestore creates it.
Update
on newer Firebase SDK the syntax changed; Firebase is FirebaseFirestore and setData is deprecated in favor of set + SetOptions.
FirebaseFirestore.instance.
collection('tags').
document(tag).
set(data, SetOptions(merge: true))
@Doug is right, there is an option in the Flutter Firestore API:
Firestore.instance.
collection('tags').
document(tag here).
setData(data, merge: true)
From the doc:
setData(Map<String, dynamic> data, {bool merge: false}) → Future<void>
Writes to the document referred to by this DocumentReference. If the document does not yet exist, it will be created.
If merge is true, the provided data will be merged into an existing document instead of overwriting.
Compare that with the doc from updateData
, which explicitly fails.
updateData(Map<String, dynamic> data) → Future<void>
Updates fields in the document referred to by this DocumentReference.
If no document exists yet, the update will fail.
Use set
on the document and provide a SetOptions
with merge: true
. From the docs:
Sets data on the document, overwriting any existing data. If the document does not yet exist, it will be created.
If SetOptions are provided, the data will be merged into an existing document instead of overwriting.
var collection = FirebaseFirestore.instance.collection('collection');
collection
.doc('doc_id')
.set(yourData, SetOptions(merge: true));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With