I want to load and cast a structure from a mongoDB with a few different document types that can nest them-selfes. Let's say we have three different struct types, with one parent and two children
type Parent struct {
ID bson.ObjectId `bson:"_id,omitempty`
Title string
Description string
NestedObjects []*Parent
}
type ChildA struct {
Parent
DateFrom time.Time
DateTo time.Time
}
type ChildB struct {
Parent
Options []string
}
The idea is to have a root-document holding other ChildA
or ChildB
documents. So an example document could look like this:
{
"Title": "test event",
"Description": "description goes here",
"NestedObjects": [
{
"Title": "test event",
"Description": "description goes here",
"NestedObjects": [],
"Options": ["foo", "bar"]
}
],
DateFrom: ISODate(...),
DateTo: ISODate(...)
}
How can I now cast them dynamically into a struct (of the correct type)? The root-document is of the Type ChildA
and the first nested document of the type ChildB
. And the result I want is some kind of static type []Parent
which can be dynamically be casted to the sub types, somehow like this (pseudo-code)
for _ ele := range results {
if ele typeof ChildA {
...
}
if ele typeof ChildB {
...
}
}
(Just for some explaination: I want to build events like ToDo Lists, Polls, and some others which can contain each other. So like a event "Netflix&chill" can have a Poll & ToDos, example: ToDos: "Buy popcorn", "Decide which movie to watch -> [Poll: "Jurassic Park", "Inception", ...]".)
First of all your NestedObjects []*Parent
is a slice of Parent
s, not children.
Secondly, it is not clear how you are going to discriminate your children and what you would expect in the result of, for example, Collection.Find().One(?)
It may worth to read Unstructured MongoDB collections with mgo for good examples of how to use bson.* types.