我正在制作一個課程管理應用程式。我正在嘗試將一門課程添加到課程串列中
教師將為自己創建課程的程序,然后應將其添加到他作為欄位的陣列中。
例如講師 DR.Reema 將添加課程 MATH。ai 應該保存在課程串列中。
我試圖實作的是將課程名稱保存在當前用戶的陣列中。我的問題是我不知道如何讓當前用戶在教師串列中搜索它以將課程添加到他的串列中
我們的 Firebase 截圖:

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])
});
uj5u.com熱心網友回復:
作為一個很好的起點,像這樣的函式應該對您有用:
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"));
}
您不需要確保該課程已經存在于陣列中,因為如果該.update()方法檢測到已經存在具有其名稱的欄位,則不會添加新的欄位。
更新的答案
既然你告訴我你不知道講師的名字,而只知道電子郵件地址,這是那些講師檔案的一個欄位,這樣的東西應該適合你:
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"))
})
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/344862.html
標籤:火力基地 扑 镖 谷歌云firestore
