【问题标题】:How to update field in firestore document?如何更新firestore文档中的字段?
【发布时间】:2021-10-12 17:00:38
【问题描述】:

我正在尝试仅更新文档中的一个字段 但是如果我没有给它们一个值,另一个字段将设置为 null。

这是我的代码

Future updateUser({
    String? uid,
    String? displayName,
    String? email,
    String? phoneNumber,
    String? photoURL,
    String? creationTime,
  }) async {
    return await usersCollection.doc(uid).update({
      "id": uid,
      "displayName": displayName,
      "email": email,
      "phoneNumber": phoneNumber,
      "photoURL": photoURL,
      "type": 'Not Admin',
      "isApproved": false,
      "creationTime": creationTime,
    });
  }

我是否可以在不为要更新的每个字段创建方法的情况下更新单个字段?

因此,如果我想更新 displayName,我只需将 displayName 传递给该方法,而其他字段保持不变。

请帮助我找到更好的方法来做到这一点

【问题讨论】:

    标签: flutter dart google-cloud-firestore


    【解决方案1】:

    下面是一个做你想做的事的方法的例子:

    Future updateUser({
      String? uid,
      String? displayName,
      String? email,
      String? phoneNumber,
      String? photoURL,
      String? creationTime,
    }) async {
      Map<String, dynamic> userData = {
        "type": 'Not Admin',
        "isApproved": false,
      };
      if (uid != null) {userData['uid'] = uid;}
      if (displayName != null) {userData['displayName'] = displayName;}
      if (email != null) {userData['email'] = email;}
      if (phoneNumber != null) {userData['phoneNumber'] = phoneNumber;}
      if (photoURL != null) {userData['photoURL'] = photoURL;}
      if (creationTime != null) {userData['creationTime'] = creationTime;}
      return await userCollection.doc(uid).update(userData);
    }
    

    如果 typeisApproved 从未更改,您可以从 userData 映射中删除它们。

    【讨论】:

      【解决方案2】:

      有两种方式:

        void setData({
          required String path,
          required Map<String, dynamic> data,
        })  {
          final reference = FirebaseFirestore.instance.doc(path);
           reference.set(data, SetOptions(merge: true));
        }
      

        void updateData({
          required String path,
          required Map<String, dynamic> data,
        }) {
          final reference = FirebaseFirestore.instance.doc(path);
           reference.update(data);
        }
      

      只更新一个字段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-10
        • 1970-01-01
        • 1970-01-01
        • 2019-08-14
        • 2018-11-22
        • 1970-01-01
        • 2021-09-15
        相关资源
        最近更新 更多