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

前端 未结 6 1203
慢半拍i
慢半拍i 2020-12-13 11:22

I have kotlin data class

data class Client(

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


        
6条回答
  •  醉梦人生
    2020-12-13 11:38

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

    inline fun 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()

    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
    

提交回复
热议问题