Home > Software design >  How to update field in firestore document?
How to update field in firestore document?

Time:10-13

I'm trying to update only one field in the document but the other field is set to null if I didn't give them a value.

this is my code

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,
    });
  }

Can I update a single field without creating a method for every field I want to update?

so if I want to update displayName I just pass displayName to the method and leave other fields without change.

please help me to find a better way to do that

CodePudding user response:

Here's an example of one way to do what you want:

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);
}

If type and isApproved never changes, you can remove those from the the userData map.

CodePudding user response:

There are two ways:

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

and

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

Update it's only for one field.

  • Related