I have created a Firestore database that contains objects of a user-defined class named "Courses" as its documents. Now I want to read these documents in a transaction as a list together with their document IDs. I can store these documents in a list however I can not figure out how to retrieve the document IDs of these documents. As far as I know, a transaction operating on a Firestore database returns a document snaphot when it reads this database with the get method. I want to extract the document ids of these documents from this document snaphot but I don’t know how to do that.
Below is the picture of my database.
Below is the android studio java code for my user defined class "Courses.
import com.google.firebase.firestore.Exclude;
import java.io.Serializable;
public class Courses implements Serializable {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Exclude
private String id;
private String courseName, courseDescription, courseDuration;
public Courses() {
}
.
public Courses(String courseName, String courseDescription, String courseDuration) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.courseDuration = courseDuration;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public String getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(String courseDuration) {
this.courseDuration = courseDuration;
}
}
I tried the following code in java to store the documents in my firestore database as a list:
DocumentSnapshot doclist = transaction.get(document1);
List courses1 = doclist.toObject(Courses.class);
But I do not know how to get the document ids from the above "courses1" List.
2
Answers
You can get document id using
document.getId()
. You will have to traverse every document in the query, get its document id and save it back in yourcourses
data object. Read more about it on firebase docs.You can only run a transaction on a FirebaseFirestore object. Since you didn’t share your code, I imagine that it looks like this:
The above code will read the "usk…O18" document in a transaction, it will read the document ID inside the transaction and it will update the value of the
id
field. I’m not sure why would you need the document ID, as you already know that ID because it is used when you create the reference that points to that document.