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

前端 未结 6 1303
慢半拍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:26

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

    interface HasId {
        var id : String
    }
    
    inline fun  DocumentSnapshot.toObjectWithId(): T {
        return this.toObject(T::class.java)!!.also {
            it.id = this.id
        }
    }
    
    inline fun  QuerySnapshot.toObjectsWithId(): List {
        return this.documents.map {
            it.toObjectWithId()
        }
    }
    

    And usage:

    data class User(
        @get:Exclude
        override var id: String,
        ...
    ): HasId
    
    
    val user = documentSnapshot.toObjectWithId()
    val users = querySnapshot.toObjectsWithId()
    

提交回复
热议问题