How to update a value in firebase database that has a randomly generated ID/KEY flutter

Viewed 64

enter image description here

I want to change the name of the user.

I found out that i can change the name by doing this:

changeValue(valueMap,username){
    FirebaseFirestore.instance.collection('users')
        .doc('WAdq4CwPD471gx92ncBW')
        .update(valueMap);
  }
Map<String, String> valueMap = {
   'name': _name,
  };

dataBase.changeValue(valueMap);

But for that I need to get that randomly generated KEY/ID, So I need, change the name by using the username of that user, how can I do that?

1 Answers

There are several ways to do this. First, if you have the user's username, you can use this function below to get the document id.

QuerySnapshot<Map<String, dynamic>> collection = await FirebaseFirestore
  .instance
  .collection('users')
  .where('username', isEqualTo: username)
  .get();
if (collection.docs.isNotEmpty) {
  String docId = collection.docs.first.id;
  // pass this docId to changeValue(valueMap, username, docId);
} else {
  print('username does not exist');
}

Then call changeFunction with the docId like this.

changeValue(valueMap, username, docId){
  FirebaseFirestore.instance.collection('users')
    .doc(docId)
    .update(valueMap);
}
Related