skip to Main Content

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.

enter image description here

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


  1. 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 your courses data object. Read more about it on firebase docs.

    db.collection("collection-name")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            // map the document to the data class
                            Courses courses = document.toObject(Courses.class);
                            // add document Id to each object
                            courses.setId(document.getId());
                            // add each course to the list
                            coursesList.add(courses);
    
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
    
    Login or Signup to reply.
  2. You can only run a transaction on a FirebaseFirestore object. Since you didn’t share your code, I imagine that it looks like this:

    DocumentReference docIdRef = db.collection("Courses").document("usk...O18");
    db.runTransaction(new Transaction.Function<Void>() {
        @Override
        public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {
            DocumentSnapshot snapshot = transaction.get(docIdRef);
    
            String docId = snapshot.getId();
            transaction.update(docIdRef, "id", docId);
    
            return null;
        }
    }).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "Transaction success!");
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Transaction failure.", e);
        }
    });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search