Sarvesh Bhatnagar
Sarvesh Bhatnagar

Reputation: 1122

How can I use .updateData() instead of .setData() in flutter firestore even when document does not exist

I am trying to do something along the lines that, if there does not exist a document then do setData and if the document exist, do update data... I have tried this(the code below), it seems to work but I am concerned that what if when I launch the app and the error message changes.

Future updateReference(
    String phoneNumber,
  ) async {
    try {
      return await mCollectionRef.document(phoneNumber).updateData({
        uid: true,
      });
    } on PlatformException catch (error) {
      print(error.message.substring(0, 9));
      if (error.message.substring(0, 9) == 'NOT_FOUND') {
        return await mCollectionRef.document(phoneNumber).setData({
          uid: true,
        });
      }
    }
  }

Is there any other way in which I can achieve this?

Upvotes: 4

Views: 1145

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317712

If you want to update or create a document if it doesn't already exist, you can just pass merge: true as the second argument to setData().

Upvotes: 2

Related Questions