Home > OS >  How to calculate read/writes on Firestore operation?
How to calculate read/writes on Firestore operation?

Time:01-19

I already know that having a direct path to a document id would result in a single read from the firestore through using the get() function. I am trying to retrieve a document fields value so I use FirebaseFirestore.instance.collection('users').doc(userUid).get() to get the documentSnapshot, then use await _userCollection.then((value) => value.get("field name")) to get the document field value. I do this to get "n" fields.

So, my question is would the second get() ,used to retrieve each document field, be calculated in the read costs or is it only the get() ,used to retrieve the documentSnapshot itself, which should be calculated.

Here is my full code:

_setStoreOwnerObjByFetchingUserData(String userUid) async {

  Future<DocumentSnapshot<Map<String, dynamic>>> _userCollection =
  FirebaseFirestore.instance.collection('users').doc(userUid).get();

  await StoreOwner().updateOwnerData(
      userUid,
      await _userCollection.then((value) => value.get("shopName")),
      await _userCollection.then((value) => value.get("shopAddress")),
      await _userCollection.then((value) => value.get("shopType")),
      await _userCollection.then((value) => value.get("shopSize")),
      await _userCollection.then((value) => value.get("ownerName")),
      await _userCollection.then((value) => value.get("ownerNumber")),
      await _userCollection.then((value) => value.get("subscriptionStatus")));
}

CodePudding user response:

Would the second get() ,used to retrieve each document field, be calculated in the read costs or is it only the get() ,used to retrieve the documentSnapshot itself, which should be calculated.

You only pay for the "get() used to retrieve the DocumentSnapshot". Once the asynchronous get() operation is complete the DocumentSnapshot is in memory in your app and you can call its get() method as many times as you want without any Firestore based cost.


THEREFORE it appears that in your code you query several times the database when it is not necessary. You should adapt it as follows:

_setStoreOwnerObjByFetchingUserData(String userUid) async {

  Future<DocumentSnapshot<Map<String, dynamic>>> _userCollection =
  FirebaseFirestore.instance.collection('users').doc(userUid).get();

  var docSnapshot = await _userCollection;

  await StoreOwner().updateOwnerData(
      userUid,
      docSnapshot.get("shopName"),
      docSnapshot.get("shopAddress"),
      //...
}
  • Related