Getting DocumentID when decoding Firestore struct with custom decodable

Viewed 428

I have the following struct

struct Vehicle: Codable, Identifiable {
    @DocumentID var id: String?
    var name: String
}

As long as I use the default Swift decoder I can load Firestore entries without any issue (using document.data(as: ), and id contains the document ID.

However I now need a custom decode function inside that struct, and that's where things go wrong.

I can load all fields without any issue, but the document ID is not filled out.

I tried like this:

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
    
        if let id = try container.decodeIfPresent(DocumentID<String>.self, forKey: .id) {
            self.id = id.wrappedValue
        }

But it gives me nil.

I found some other answers but they talk about DocumentReference which is a type that doesn't (or no longer?) exist.

How can I solve this?

Thanks

2 Answers

Decode the Document ID using:

_id = try container.decode(DocumentID<String>.self, forKey: .id)

for the corresponding variable:

@DocumentID var id: String?

This will place the document ID into the ID variable (note the required "_" before id).

To clarify, a DocumentReference is an object that holds the path to a firestore document and is the object you would call your platforms equivalent of .get() to retrieve data through a DocumentSnapshot. I am not terribly familiar with swift, but when decoding the object, you should be able to reference the ID as needed from the documentID property rather than the .data() method

Source: iOS Document Snapshot ID

Related