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

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

    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.

提交回复
热议问题