androidfirebasekotlingoogle-cloud-firestore

Is there a way to map my document id with toObject?


I'm deserializing an entire document, to keep things in handy and prevent me to check for each value and construct the object I use

myList.add(documentSnapshot.toObject(House::class.java))

Now, lets say House is this

data class House(val name:String,val:address:String)

Now, if I want to also get the House document Id and put it inside my document I do this

data class House(val houseId:String,val name:String,val:address:String)

But after doing that , the first line of code transforms into this

 val houseId = documentSnapshot.id
 val houseName = docuementSnapshot.getString("name")
 val houseAddress = documentSnapshot.getString("address")
 myList.add(House(houseId,houseName,houseAddress))

What I want to do is use .toObject() to also map that extra field that is the document id inside of it because if the House object expands in size, I will need to hand write again each property, and now think that house has 100 properties and I just need the id of it inside the object. I will need to write off 99 get fields to just place the document Id inside that house object.

Is there a way to map that id to the object without doing the above and just placing .toObject ?

Thanks


Solution

  • What I want to do is use .toObject() to also map that extra field that is the document id

    This will be possible only if the document already contains the id property that holds the document id as a value. If you only have the name and the address, then you cannot map the id, because it doesn't exist in the document. To be able to map all those three properties you should update each and every document in that collection so it contains the document id. If you have lots of documents in the collection, I recommend you use batch writes.

    Right after that, you'll be able to use:

    val house = documentSnapshot.toObject(House::class.java)
    

    And now this house object will contain the id too.