19

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?

7 Answers 7

31

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

7
  • What I'm trying to do is get the id into my Client model so that I can reference on click in my list view. I'm not seeing any way to keep a reference to it. Commented Oct 29, 2017 at 18:07
  • Then your question has no business to do with firebase! (depending on your answer too.) you could create any custom builder you want.
    – amrro
    Commented Oct 29, 2017 at 23:08
  • 1
    Does that answer your question?
    – amrro
    Commented Oct 31, 2017 at 1:40
  • Hey, can you say something about getting the document id that satisfies some constraints(we can use queries) in Javascript? Commented Jan 2, 2018 at 7:06
  • Hello @DivyaGalla Sorry for late response. But I guess this would help you, and constrains like what? firebase.google.com/docs/reference/js/…
    – amrro
    Commented Jan 13, 2018 at 16:40
31

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.

4
9

I just improved the solution of @iCediCe, and add methods to DocumentSnapshot and QuerySnapshot.

interface HasId {
    var id : String
}

inline fun <reified T : HasId> DocumentSnapshot.toObjectWithId(): T {
    return this.toObject(T::class.java)!!.also {
        it.id = this.id
    }
}

inline fun <reified T : HasId> QuerySnapshot.toObjectsWithId(): List<T> {
    return this.documents.map {
        it.toObjectWithId<T>()
    }
}

And usage:

data class User(
    @get:Exclude
    override var id: String,
    ...
): HasId


val user = documentSnapshot.toObjectWithId<User>()
val users = querySnapshot.toObjectsWithId<User>()
1
  • I'm not sure how you got this to work. In order for the firebase (de)serializer to work, your User class would need a no-parameter constructor. id being a non-nullable var destroys that ability? Commented May 28, 2019 at 14:31
8

Here is how I solved the problem.

data class Client(
    val name: String = "",
    val email: String = "",
    val phone: String ="",
    @get:Exclude var id: String = "") {
constructor():this("","","")
}

I use @get:Exclude on the id to make sure the id doesn't get sent to Firestore on save, and then when fetching the list of clients do:

snapshot.documents.mapTo(list) {
            var obj = it.toObject(Client::class.java)
            obj.id = it.id
            obj
        }

Setting the id of the new object to the id of the document reference.

7

I solved it by creating a extension method on QueryDocumentSnapshot like this:

inline fun <reified T : HasId>QueryDocumentSnapshot.toObjectWithId(): T {
    val model = this.toObject(T::class.java)
    model.id = this.id
    return  model
}

Now I can map like this (which I find to look nice and clean):
myModelWithId = it.toObjectWithId<MyModel>()

For this to work I made a simple hasId interface that the model needs to implement:

interface HasId{
    var id : String
}

@IgnoreExtraProperties
data class MyModel(
        @get:Exclude override var id : String    = "",
        val data                     : String    = "",

): Serializable, HasId
1
  • 1
    Brilliant! Helped me a lot. Also, still amazes me how Kotlin can make your life so much easier.... Commented Apr 15, 2018 at 5:14
2

2021 using Kotlin: the easiest way it to include it to your data class like this example :

@Parcelize
data class Level(
    var name:String?=null,
    var order:Int=0,
    var parentCycleId:String?=null,
    var totalExercices:Int=0,
    @DocumentId
    val id: String?=null,
):Parcelable

and the id will be automatically assigned by firestore database

i get data via a listener like this :

        firestoreDatabase.collection("levels")
        .whereEqualTo("parentCycleId",sharedData.getSelectedCycle().id!!)
        .orderBy("order")
        .addSnapshotListener(object : EventListener<QuerySnapshot> {
            @SuppressLint("NotifyDataSetChanged")
            override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {
                if (error != null) {
                    Log.e("ZEADEV",error.message.toString())
                    return
                }
                for (dc: DocumentChange in value?.documentChanges!!) {
                    if (dc.type == DocumentChange.Type.ADDED) {

                        val retrievedLevel: Level = dc.document.toObject(Level::class.java)
                                    levelList.add(retrievedLevel)
                        }
                    }
                   levelAdapter.notifyDataSetChanged()
                }
            })

and the retrieved data contain document id that you can get it by caling for this example

retrievedLevel.id
0

I just fetch an id from Firestore before and set it as a field on my object before I create it in Firebase:

    override fun addTodo(todo: Todo) =
    Completable.fromAction {
        val id = firestore
            .collection(COLLECTION_TODOS)
            .document()
            .id

        val newTodo = todo.copy(id = id)

        firestore
            .collection(COLLECTION_TODOS)
            .document(id)
            .set(newTodo)
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.