CodableFirebase
CodableFirebase copied to clipboard
Is that possible to decode some field which save as DocumentReference?
I'd like to do something like relationship DB
Model and Event are both Documents
and Event is one of Model's field saved as DocumentReference .
for examplae:
struct Model: Codable {
let docID: String
let eventRef:DocumentReference ////// . <------- it's a DocumentReference
}
struct Event:Codable {
let eventName:String
}
I'd like to fetch both Model & Event just use onetime method get() below:
let ref = FirestoreService.shareinstance.db.collection("CollectionPath").document("DocumentID")
ref.getDocument(completion: {doc, error in
if let doc = doc {
let model = try! FirestoreDecoder().decode(Model.self, from: (doc.data())!)
print(model) //// succeed to fetch Model
print(model.eventRef) ///// this is DocumentReference
////////do something to get model.eventRef.eventName
}
})
and is possible to fetch eventRef.eventName but not doing getDoc again?
I try to this
let event = try! FirestoreDecoder().decode(Event.self, from: (model.playEventRef)
but it show error: "Cannot convert value of type 'DocumentReference' to expected argument type '[String : Any]'"
I don't want to get() again like below:
model.playEventRef.getDocument(completion: .......)
It's a another asyn fetch method. It's not good for me
I also add
extension DocumentReference: DocumentReferenceType {}
but it seems for encode not for decode as you say.
so is possible to get DocumentReference from getData() just fetch once?
Hey! I'm trying to do something similar. Is decode a "DocumentReference" available? If no, any thoughts of how to accomplish that?
Hi! Thanks for asking this question! Yes, you can decode DocumentReference
and please refer to README to see the steps that you have to take. However, to load the underlying model of DocumentReference
you will have to make an async call and use decoder again... To make it nicer, I would recommend taking a look at some Futures or Observables library that will allow you to make it in a more declarative way.
@alickbass, can you show little example for decode Reference in async. If I do it in Initializer it doesn’t work, returns result later because it’s not async