如何使用 Flutter 更新云 Firestore 上文档中的字段?

Blo*_*oss 12 dart firebase flutter google-cloud-firestore

我尝试更新我的 firestore 数据库字段。

  Future<void> approveJob(String categoryId) {
Run Code Online (Sandbox Code Playgroud)

数据库中的注释行已更新。但我硬编码了uid。没有商店可以获取uid吗?

   //return _db.collection('jobs').document('25FgSmfySbhEPe1z539T').updateData({'isApproved':true});


   return _db
        .collection('jobs')
        .where("categoryId", isEqualTo: categoryId)
        .getDocuments()
        .then((v) {
          try{
            v.documents[0].data.update('isApproved', (bool) => true,ifAbsent: ()=>true);

// No Errors. But not updating

         }catch(e){
            print(e);
          }
    });
  }
Run Code Online (Sandbox Code Playgroud)

awa*_*aik 19

===2020年12月===

Flutter 中更新 Firestore 文档有两种方法:

  1. set()- 在文档上设置数据,覆盖任何现有数据。如果该文档尚不存在,则会创建该文档。
  2. update()- 更新文档中的数据。数据将与任何现有文档数据合并。如果尚不存在文档,则更新将失败。

因此,要更新现有文档中的确切字段,您可以使用

FirebaseFirestore.instance.collection('collection_name').doc('document_id').update({'field_name': 'Some new data'});
Run Code Online (Sandbox Code Playgroud)


Cop*_*oad 7

  • 要更新文档中的值:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('doc_id') 
        .update({'key' : 'value'}) // <-- Updated data
        .then((_) => print('Success'))
        .catchError((error) => print('Failed: $error'));
    
    Run Code Online (Sandbox Code Playgroud)
  • 更新文档中的嵌套值。

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('doc_id')
        .update({'key.foo.bar' : 'nested_value'}) // <-- Nested value
        .then((_) => print('Success'))
        .catchError((error) => print('Failed: $error'));
    
    Run Code Online (Sandbox Code Playgroud)
  • 向现有文档添加新值。

    var collection = FirebaseFirestore.instance.collection('collection');
    collection
        .doc('doc_id')
        .set(yourData, SetOptions(merge: true)); // <-- Set merge to true.
    
    Run Code Online (Sandbox Code Playgroud)


tzo*_*urn 0

要更新文档中的字段,您只需遵循文档即可。

关于如何获取documentID,你可以按照这里的描述进行

另请记住,您可以通过事务更新数据

让我知道这是否有帮助。


归档时间:

查看次数:

33698 次

最近记录:

2 年,7 月 前