Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting DocumentID when decoding Firestore struct with custom decodable

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

like image 802
Joris Mans Avatar asked May 24 '26 07:05

Joris Mans


1 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).

like image 77
Will Alexander Avatar answered May 26 '26 05:05

Will Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!