如何使用帮助DocumentID更新Cloud Firestore文档字段?

时间:2020-05-16 09:01:00

标签: flutter dart google-cloud-firestore

在这里,我试图借助documentID(String keyId)更新用户的退出时间。当用户在给定的INPUTFIELD中添加DOCUMENTID或keyId和Exit-time:Value(获取更新)时完成更新.cloud_database中的数据正在以(KeyId(KzlWLHJc0di6QziewVV7)=> InputField =>更新完成的方式进行更新在cloud_database中。)

1st Code:(The below code working & updating properly in database)

String KeyId;
QuerySnapshot qs = await Firestore.instance.collection('student entry').getDocuments();
qs.documents.forEach((DocumentSnapshot snap) async {
  if(snap.documentID == keyId )  {
    DocumentReference documentReference = Firestore.instance.collection(
        'student entry').document(keyId);
    documentReference.updateData({
        'Exit-time': date,

    });

但是现在我为每个用户添加了身份验证。数据库为每个用户分别存储数据。现在我不知道我可以在第二代码中做什么其他修改以使工作过程像上述代码一样。

  2nd code:

  String keyId;
  CollectionReference vaultCollection =  Firestore.instance.collection('student entry').document(uid).collection('vault');         //Where should i add keyId new code
 DocumentReference doc=vaultCollection.document();
 doc.updateData({

   'Exit-time': date,


  });      

1 个答案:

答案 0 :(得分:1)

我假设您在Document ID上要更新数据。您可以将setData函数与merge: true一起使用。不必获取数据即可对其进行更新。

在您的示例中,KeyId是您要在其中更新数据的Document ID

第一个代码

DocumentReference documentReference = Firestore.instance.collection('student entry').document(keyId);
documentReference.setData({'Exit-time': date},merge:true);

第二个密码

现在,因为您将数据存储在Sub-Collection中。仅文档参考将被更新。

DocumentReference documentReference = Firestore.instance.collection('student entry').document(uid).collection('vault').document(keyId);
documentReference.setData({'Exit-time': date},merge:true);

希望这会有所帮助。