I have two collections in firestore db 1. projects 2.users
'projects' has a field 'created_by' which hold the id of the user who created it. I want to fetch projects along with all fields of the user who created it.
Following code works but I am not sure whether it is the correct way of doing this and how do we know when the fetching of user data for every project is complete.
fun getProjects(){
val works = arrayListOf<Work>()
db.collection("projects")
.get()
.addOnSuccessListener { documents ->
for (document in documents) {
val work = Work(document.id,
document.data.get("title").toString(),
document.data.get("skills") as ArrayList<String>,
document.data.get("date_created") as Date)
works.add(work)
db.collection("users").document(document.data.get("created_by").toString()).get()
.addOnSuccessListener {
documentSnapshot ->
work.created_by = User(documentSnapshot.data?.get("name").toString(),
documentSnapshot.data?.get("mob").toString(),
documentSnapshot.data?.get("role").toString(),
documentSnapshot.data?.get("rating").toString(),
documentSnapshot.data?.get("skills") as ArrayList<String>
)
Log.d("works", works.toString())
}
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Error getting documents: ", exception)
}
}