What is the best way to store polymorphic objects in Firestore?
Example: Assuming a "base" object, three others inherit from it. I think of storing specific objects all in the same collection. Can the firestore understand, for example, queries with field indexes that may exist in one document and not in the other?
The structure is:
BaseObject
A extends BaseObject
B extends BaseObject
C extends BaseObject
So I think of storing A, B and C in the same collection and casting according to a "type" attribute commom in superclass...
So at the time of the query, I thought of simply knowing the type and casting. But, I really don't know if firestore supports create one or more indexes to perform query if some attribute exists or not in one or more documents.
Is possible?
Yup, your approach sounds possible to me. Storing multiple types in a single collection is one of the ways to deal with the scenario, with its own set of advantages and disadvantages.
When you're reading data back, you can't simply cast the value through. You'll have to read the type field yourself and request the correct subclass in the call to toObject()
, as the Firebase SDK won't know anything about the meaning of that field.
I'd recommend giving it a try, and reporting back if you run into more concrete problems.