Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Firestore update if exist if not create

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 this
Firestore.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?

like image 301
Daibaku Avatar asked Sep 12 '18 00:09

Daibaku


People also ask

Does firestore Create collection if not exists?

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.


2 Answers

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.

like image 102
stwienert Avatar answered Sep 21 '22 13:09

stwienert


Update 2021:

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));
like image 35
CopsOnRoad Avatar answered Sep 20 '22 13:09

CopsOnRoad