skip to Main Content

I use getDocData function for get one document.

 Future getDocData(String docPath) async {
    try {
      print(docPath);
      final response = await fireStore.doc(docPath).get();
      return response.data();
    } catch (e) {
      throw UnimplementedError(e.toString());
    }
  }

After i got document i updated same document with updateDocument function.

 Future updateDocument<T>(docPath, docField, data) async {
    try {
      return await fireStore.doc(docPath).set(
        {docField: data},
        SetOptions(
          merge: true,
        ),
      );
    } catch (e) {
      throw UnimplementedError(e.toString());
    }
  }

when operation done. i expect on firebase usage dasboard one read and one write operation happen but I see two read and one write operation.Is there anyway solve this issue or is it okay?

2

Answers


  1. you can Use update() instead of set() with SetOptions(merge: true) can be a good solution for reducing the number of read operations,like this

    Future updateDocument<T>(docPath, docField, data) async {
      try {
        return await fireStore.doc(docPath).update(
          {docField: data},
        );
      } catch (e) {
        throw UnimplementedError(e.toString());
      }
    }
    
    Login or Signup to reply.
  2. I have tried updating the document with set and update and observed the reads and writes like below :

    With set() I got two reads and one write in the dashboard. set() with merge instead of updating existing documents will create a new document copying existing fields while retaining the same doc id. That is where I got one extra read operation.

    With update() it is updating the existing document and will get one read and one write operation.

    The docfield passed as value should be a key, which means it needs to be passed with [] brackets. Take a look at the sample code.

    Future updateDocument<T>(docPath, docField, data) async {
        try {
          return await fireStore.doc(docPath).update(
            {[docField]: data}, // ⇐ notice
          );
        } catch (e) {
          throw UnimplementedError(e.toString());
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search