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

Great solutions. Looks like Firestore came up with a way to add an annotation to your model to solve this problem.

You could do:

@DocumentId
val documentId: String

And then Firestore will generate that field when calling toObject or toObjects. When you .set() the document in Firestore, it will exclude this field.


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