Midhilaj
Midhilaj

Reputation: 4987

I need to update document if exists otherwise create

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'

Upvotes: 2

Views: 2571

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138969

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().

Upvotes: 5

ultraGentle
ultraGentle

Reputation: 6329

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).

Upvotes: 1

Related Questions