简体   繁体   English

Firestore 可编码不包括 Firestore DocumentID

[英]Firestore encodable not including Firestore DocumentID

Im using Firebase Firestore in my project, and I have figured out that I need to use @DocumentId to properly decode firebase "_id" property into my codable struct.我在我的项目中使用 Firebase Firestore,我发现我需要使用 @DocumentId 将 firebase“_id”属性正确解码到我的可编码结构中。

My issue is that I need to save the encoded object (for now I'm using userdefaults) and re-decode the object later on in my apps lifecycle.我的问题是我需要保存编码的 object(目前我使用的是 userdefaults)并稍后在我的应用程序生命周期中重新解码 object。

When I encode my Firestore object with Firestore.encode, it loses the id property as it becomes encoded to [String: Any] so when I try to decode the fetched pre-encoded object, I'm unable to do so.当我使用 Firestore.encode 对我的 Firestore object 进行编码时,它会丢失 id 属性,因为它被编码为 [String: Any] 所以当我尝试解码获取的预编码 object 时,我无法这样做。

For now I am storing the ID property separately, and re-adding it to the object once decoded.现在我单独存储 ID 属性,并在解码后将其重新添加到 object。

Is this the correct way to handle Firestore codable?这是处理 Firestore 可编码的正确方法吗? Or is there a cleaner way to encode and then decode Firestore encoded objects?或者是否有更简洁的方法来编码然后解码 Firestore 编码的对象?

As discussed here正如这里所讨论的

The solution is to explicitly ask for the DocumentID wrapping of DocumentReference and then manually unwrap yourself.解决方案是显式请求 DocumentReference 的 DocumentID 包装,然后自己手动解包。 It looks like this:它看起来像这样:

 ref = try container.decode(DocumentID<DocumentReference>.self, forKey: .ref).wrappedValue

Also check these similar cases for more information:另请检查这些类似案例以获取更多信息:

How can I get the document ID when using Codable in Firestore? 在 Firestore 中使用 Codable 时如何获取文档 ID?

Getting DocumentID when decoding Firestore struct with custom decodable 使用自定义解码器解码 Firestore 结构时获取 DocumentID

Getting document ID when decoding firestore document using Swift Codable 使用 Swift Codable 解码 firestore 文档时获取文档 ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM