我想从 mongoDB 加载并转换一个结构,该结构具有一些可以嵌套的不同文档类型。假设我们有三种不同的结构类型,有一个父类和两个子类
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
}
想法是让根文档包含其他 ChildA
或 ChildB
文档。因此,示例文档可能如下所示:
{
"Title": "test event",
"Description": "description goes here",
"NestedObjects": [
{
"Title": "test event",
"Description": "description goes here",
"NestedObjects": [],
"Options": ["foo", "bar"]
}
],
DateFrom: ISODate(...),
DateTo: ISODate(...)
}
我现在如何将它们动态地转换为一个结构(正确类型)?根文档的类型为 ChildA
,第一个嵌套文档的类型为 ChildB
。我想要的结果是某种静态类型 []Parent
可以动态地转换为子类型,有点像这样(伪代码)
for _ ele := range results {
if ele typeof ChildA {
...
}
if ele typeof ChildB {
...
}
}
(仅作一些解释:我想构建诸如 ToDo 列表、民意调查和其他一些可以相互包含的事件。因此,像“Netflix&chill”这样的事件可以有一个民意调查和待办事项,例如:ToDos:“购买爆米花", "决定看哪部电影 -> [投票:《侏罗纪公园》、《盗梦空间》、...]"。)
最佳答案
首先,您的 NestedObjects []*Parent
是 Parent
的一部分,而不是子对象。
其次,您不清楚您将如何区分您的 child 以及您对结果的期望,例如 Collection.Find().One(?)
可能值得一读Unstructured MongoDB collections with mgo有关如何使用的好例子 bson.*类型。
关于mongodb - 如何在 mGo 中动态转换结果文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35149849/