skip to Main Content

I want to update a document in the firebase flutter application.
but that document might not exist in the database, first I want to search for the document using one of its fields, and if a document is found I want to update a value, and if not then nothing happens.

I have a user modal that has these fields.

final Map user;
final String mobile;
final String business_name;
final String business_address;
final String aadhar;
final String pan;
final bool isPhoneVerified;
final int growScore;
final String sector;
final String profile_picture;
final String business_picture;
final String uid;
final String about;

I want to search document using mobile field and update its growScore.

here’s what I am trying but not working

  updateGrowScore(String phoneNumber, String post_type) async {
    await ref
        .watch(firestoreProvider)
        .collection("my_users")
        .where("mobile", isEqualTo: phoneNumber)
        .get()
        .then((value) => value.docs.map((e) {
              ref
                  .watch(firestoreProvider)
                  .collection('my_users')
                  .doc(e.id)
                  .update({
                'growScore': FieldValue.increment(post_type == "Bad" ? -5 : 5)
              });
              print("successfully updated");
            }));
  }

2

Answers


  1. if the doxument do not exist, then when you call the get() on the Query, it will return an empty List, so if there is no document exists, you will map() an empty List so nothing will happen.

    Login or Signup to reply.
  2. Try this function:

    updateGrowScore(String phoneNumber, String post_type) async {
      QuerySnapshot querySnapshot = await ref
          .watch(firestoreProvider)
          .collection("my_users")
          .where("mobile", isEqualTo: phoneNumber)
          .get();
    
      List documentIds = querySnapshot.map((doc) => doc.id).toList();
      for (int index = 0; index < documentIds.length; index++) {
        final currentDoxId = documentIds[index];
    
        await ref
            .watch(firestoreProvider)
            .collection('my_users')
            .doc(currentDoxId)
            .update(
          {
            'growScore': FieldValue.increment(post_type == "Bad" ? -5 : 5),
          },
        );
        print("${currentDoxId} growScore updated");
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search