简体   繁体   中英

how to search document and update it in firebase flutter

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");
            }));
  }

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");
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM