mgo 中的模型关系
Model relationships in mgo
我正在用 mgo 编写一个数据库接口。
我的模型中的某些文档引用了其他文档。
type Child struct{
Id bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
C string
}
type Parent struct {
Id bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
A string
B Child
}
child := Child{
Id: bson.NewObjectId(),
C: "panino"
}
parent := Parent{
Id: bson.NewObjectId(),
A: "Just a string",
B: child,
}
我的目标是:
- 将这些文档嵌入代码中,
- 在 Parents 集合中存储父项,仅引用子项,
- 将 child 作为独立文档存储在 Children 集合中。
以下:
type Child struct{
Id bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
C string `bson:"-"`
}
在 1 和 2 中成功,但只有 child.Id 存储在 Children 集合中。
我是 Golang/mgo 的新手。我玩了一下 Marshaling 和 Unmarshaling,但我不太明白 Getter 和 Setter 是如何工作的。我有一种感觉,他们会成功的。
有什么线索吗?
您可能正在寻找 bson:",omitempty"
标签而不是 bson:"-"
。前者只有在该字段为空时才会省略该字段,而不是一直省略。或者,您也可以使用仅用于引用的辅助 ChildReference
类型。同一个集合可以使用不同的类型。
顺便说一句,请注意,尽管在某些情况下使用了这种做法,但您 不必 在所有情况下都将集合名称存储在文档 ID 旁边。定义明确的模式最常见的做法是简单地存储文档 ID(例如,{"person_id": 123}
意思很清楚)。
我正在用 mgo 编写一个数据库接口。 我的模型中的某些文档引用了其他文档。
type Child struct{
Id bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
C string
}
type Parent struct {
Id bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
A string
B Child
}
child := Child{
Id: bson.NewObjectId(),
C: "panino"
}
parent := Parent{
Id: bson.NewObjectId(),
A: "Just a string",
B: child,
}
我的目标是:
- 将这些文档嵌入代码中,
- 在 Parents 集合中存储父项,仅引用子项,
- 将 child 作为独立文档存储在 Children 集合中。
以下:
type Child struct{
Id bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
C string `bson:"-"`
}
在 1 和 2 中成功,但只有 child.Id 存储在 Children 集合中。 我是 Golang/mgo 的新手。我玩了一下 Marshaling 和 Unmarshaling,但我不太明白 Getter 和 Setter 是如何工作的。我有一种感觉,他们会成功的。 有什么线索吗?
您可能正在寻找 bson:",omitempty"
标签而不是 bson:"-"
。前者只有在该字段为空时才会省略该字段,而不是一直省略。或者,您也可以使用仅用于引用的辅助 ChildReference
类型。同一个集合可以使用不同的类型。
顺便说一句,请注意,尽管在某些情况下使用了这种做法,但您 不必 在所有情况下都将集合名称存储在文档 ID 旁边。定义明确的模式最常见的做法是简单地存储文档 ID(例如,{"person_id": 123}
意思很清楚)。