简体   繁体   English

如何在 firebase flutter 中搜索文档并进行更新

[英]how to search document and update it in firebase flutter

I want to update a document in the firebase flutter application.我想更新 firebase flutter 应用程序中的文档。 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.我想使用移动字段搜索文档并更新其 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:试试这个 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.如果文档不存在,那么当您在查询上调用 get() 时,它将返回一个空列表,因此如果不存在文档,您将 map() 一个空列表,这样什么都不会发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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