Home > database >  adding to array for a specific user in firebase dart
adding to array for a specific user in firebase dart

Time:11-02

I'm making a course management app. and I'm trying to add a course to the list of courses

the process as that the instructor will create a course to himself then it should be added to the array he has as field.

for instance the instructor DR.Reema will add course MATH. ai should be saved in Courses List.

what im trying to achieve is to save course name in field courses which is an array for the current user. my problem is that i dont know how to get the current user to search for it in the list of instructors to add the course to his list

screenshots of our Firebase:

enter image description here

FirebaseAuth auth = FirebaseAuth.instance;

  final User? user = auth.currentUser;
  DocumentReference ref = FirebaseFirestore.instance
      .collection('Users')
      .doc('list_instructors')
      .collection('Instructor')
      .doc(user!.uid);
ref.update({
    'Courses': FieldValue.arrayUnion([courseName, courseCode])
  });

CodePudding user response:

A function like this should be useful to you as a good starting point:

void UpdateUser(String userName, String courseName){
  FirebaseFirestore.instance
    .collection('Users')
    .doc('list_instructors')
    .collection('Instructor')
    .doc(userName)
    .update({'Courses': FieldValue.arrayUnion([courseName])})
    .then((value) => print("User Updated"))
    .catchError((error) => print("Failed to update user: $error"));
}

You don't need to make sure that the course is already present in the array since if the .update() method detects there is already a Field with its name, it won't add a new one.

UPDATED ANSWER

Since you told me that you don't know the Instructor names, but only the email address, which is a field of those Instructor documents, something like this should work for you:

void UpdateUser(String email, String courseName){
  FirebaseFirestore.instance
    .collection('users')
    .doc('list_instructors')
    .collection('Instructor')
    .where('email', isEqualTo: email)
    .get()
    .then((querySnapshot) => {
      querySnapshot.docs.forEach((doc) => {
        doc.reference.update({'Courses': FieldValue.arrayUnion([courseName])})
        .then((value) => print("User Updated"))
        .catchError((error) => print("Failed to update user: $error"))
      })
    });
}
  • Related