dart 如何使用Flutter更新Cloud Firestore中文档字段?

uemypmqf  于 2023-01-18  发布在  Flutter
关注(0)|答案(5)|浏览(96)

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

Future<void> approveJob(String categoryId) {

注解行在数据库上更新。但是我硬编码了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);
          }
    });
  }
ezykj2lf

ezykj2lf1#

=== 2020年12月===
Flutter中有两种更新Firestore文档的方法:

  1. set()-在文档上设置数据,覆盖任何现有数据。如果文档尚不存在,则将创建它。
  2. update()-更新文档中的数据。数据将与任何现有文档数据合并。如果文档尚不存在,更新将失败。
    因此,要更新现有文档中的确切字段,可以使用
FirebaseFirestore.instance.collection('collection_name').doc('document_id').update({'field_name': 'Some new data'});
svmlkihl

svmlkihl2#

  • 要更新文档中的值:
var collection = FirebaseFirestore.instance.collection('collection');
collection 
    .doc('doc_id') 
    .update({'key' : 'value'}) // <-- Updated data
    .then((_) => print('Success'))
    .catchError((error) => print('Failed: $error'));
  • 更新文档中的嵌套值。
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'));
  • 向现有文档添加新值。
var collection = FirebaseFirestore.instance.collection('collection');
collection
    .doc('doc_id')
    .set(yourData, SetOptions(merge: true)); // <-- Set merge to true.
rta7y2nd

rta7y2nd3#

首先,您需要确定并定位要修改的字段。

final code = Code.fromSnapshot(document);

FirebaseFirestore.instance.collection('collection_Name').doc('doc_Name').collection('collection_Name').doc(code.documentId).update({'redeem': true});

在本例中,code.documentId代码是包含快照的示例。通过使用此代码,可以访问“identifier”documentId;然后字段redeem变为真,

cmssoen2

cmssoen24#

FirebaseFirestore.instance.collection('groups').doc(chatId).collection('groupChat')
        .doc(chatId).update({
      'lastMessage': messageTextController.text.toString(),
      'lastMessageSendBy' : currentUser,
      'lastMessageTime' : Timestamp.now(),
    });
3j86kqsm

3j86kqsm5#

要更新文档中的字段,您只需遵循此文档。
关于如何获取documentID,可以按照here所述进行
还要记住,您可以使用事务更新数据。
如果有帮助请告诉我。

相关问题