Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the document ID for a Firestore document using kotlin data classes

I have kotlin data class

data class Client(

    val name: String = "",
    val email: String = "",
    val phone: String ="") {
constructor():this("","","")}

I have firestore populate the data into the class just fine, however I am at a loss trying to figure out how to get the document id into the data class without having to set it in the document itself. Is this possible?

like image 206
Curtis.Covington Avatar asked Oct 28 '17 22:10

Curtis.Covington


1 Answers

Yes, it's possible to get id without storing it, using DocumentSnapshot. I will try to build complete examples here.

I created a general Model class to hold the id:

@IgnoreExtraProperties
public class Model {
    @Exclude
    public String id;

    public <T extends Model> T withId(@NonNull final String id) {
        this.id = id;
        return (T) this;
    }
}

Then you extend it with any model, no need to implement anything:

public class Client extends Model

If I have list of clients here, trying to query the list to get only clients with age == 20:

clients.whereEqualTo("age", 20)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot documentSnapshot : task.getResult().getDocuments()) {
                        // here you can get the id. 
                        Client client = document.toObject(client.class).withId(document.getId());
                       // you can apply your actions...
                    }
                } else {

                }
            }
        });

And if you are using EventListener, you can also get the id like the following:

clients.addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
        for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
            // here you can get the id. 
            QueryDocumentSnapshot document = change.getDocument();
            Client client = document.toObject(client.class).withId(document.getId());
                       // you can apply your actions...
        }
    }
});

documentSnapshot.getId()) will get you the id of the Document in the collection without saving the id into the document.

Using Model will not let you edit any of your models, and don't forget using @IgnoreExtraProperties

like image 163
amrro Avatar answered Oct 09 '22 20:10

amrro