2

Is there any way to do an update to a document if exists else create a document. Now I am using the update method but if the document does not exist then it will throw an error message.

Firestore.instance.collection('partnerRequests').document(user.uid).updateData( {
                  DateTime.now().millisecondsSinceEpoch.toString():partnerRegistrationFormData})

Unhandled Exception: type 'PlatformException' is not a subtype of type 'String'

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Midhilaj
  • 4,905
  • 9
  • 45
  • 88

2 Answers2

5

If you are calling updateData() function, you'll only update the document if it already exists in your partnerRequests collection. If that particular document does not exist, the updateData() call will fail, with the exception you showed us.

On the other hand, in case you are calling setData() function:

docRef.setData(data, merge: true)

You'll create the document if it doesn't exist, or update it if it's already there. That's basically the difference between these two functions.

And to answer your question:

I need to update the document if exists otherwise create

You should definitely use setData().

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • okay, when it update is it remove old values for example the doc contains values a1,b1,c1 and I call setdate and if the new data only contains fleds a1 and b1 is it delete c1 or is it update a1 and b1 and keep c1? – Midhilaj Sep 23 '20 at 06:17
  • If you only want to update some fields and let the other untouched, then use update(), as explained in my answer from this **[post](https://stackoverflow.com/questions/56608046/update-a-document-in-firestore)**. – Alex Mamo Sep 23 '20 at 09:48
  • sure, now I am working on another project and at the weekend I will check this and accept this answer. Sorry for the delay – Midhilaj Sep 24 '20 at 06:22
  • @Midhilaj Ok, keep me posted. Thanks. – Alex Mamo Sep 24 '20 at 08:47
1

I believe the answer is in this thread: Firebase update vs set

Specifically, you'll want to use the method .set({dataToSet},{merge:boolean}), which will create the document if it doesn't exist, and then you choose via merge what will happen if it does already (true = update existing fields and add new ones, false = overwrite all existing data at that location).

ultraGentle
  • 5,084
  • 1
  • 19
  • 45
  • The answer from stackoverflow that you provided as an example, is for Firebase Realtime Database and the OP is asking the question about Cloud Firestore. Firebase Realtime Database and Cloud Firestore are two different products. Each one of them has different methods to update elements in the database. – Alex Mamo Jan 25 '20 at 08:18