dstew32424 2015-03-02 13:12
浏览 39
已采纳

mgo中的模型关系

I'm writing a db interface with mgo. Some documents in my model reference other documents.

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,
}

My aim is to:

  1. keep these documents embedded in the code,
  2. store parent in Parents collection with only a reference to child,
  3. store child in Children collection as a standalone document.

The following:

type Child struct{
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    C        string          `bson:"-"`
}

succeeds in 1 and 2 but only child.Id get stored in Children collection. I'm very new to Golang/mgo. I played a bit with Marshaling and Unmarshaling, but I don't quite understand how Getter and Setter work. I have the feeling they would do the trick though. Any clue?

  • 写回答

1条回答 默认 最新

  • duandi4238 2015-03-04 14:49
    关注

    You are probably looking for the bson:",omitempty" tag instead of bson:"-". The former will omit the field only if it is empty, instead of at all times. Alternatively, you can also have a secondary ChildReference type that is used on references only. It's fine to use different types with the same collection.

    As an aside, note that although that practice is used in some situations, you don't have to store the collection name next to the document id in all cases. The most common practice for well defined schemas is to store simply the document id (e.g. with {"person_id": 123} the meaning is clear).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题