douhu2370 2017-01-30 06:43
浏览 103
已采纳

在模型结构中嵌套文档

Say I have a UserModel like so:

type (
    OrderModel struct {
         ID   bson.ObjectId `json:"id" bson:"_id"`
         ...
    }

    UserModel struct {
         ...
         // What do I store here? Is this an array of strings? An array of bson.ObjectID? Or an Array of OrderModel?
         Orders  []string        `json:"orders" bson:"orders"`
         Orders  []bson.ObjectId `json:"orders" bson:"orders"`
         Orders  []OrderModel    `json:"orders" bson:"orders"`
         ...
    }
)

func (user *UserModel) PopulateOrders() {
    orders := []OrderModel{}

    // Query orders and assign to variable orders to then be assigned the the user Object
    // {magic query here}

    user.Orders = orders
}

In MongoDB, an array of ObjectIDs would be stored to reference the OrderModel documents. Later on, I have a function that will populate the Order documents like described above: PopulateOrders.

What is the best way for the case above?

  • 写回答

1条回答 默认 最新

  • duanlu1922 2017-01-30 10:01
    关注

    I would use 2 separate fields, one for the slice of IDs, and one for the slice of lazily loaded objects.

    Omit the lazily loaded object slice from saving. It could look like this:

    type UserModel struct {
         // ...
         OrderIDs []bson.ObjectId `json:"orderIDs" bson:"orderIDs"`
         Orders   []OrderModel    `json:"orders" bson:"-"`
         // ...
    }
    

    Note that I intentionally did not exclude Orders from JSON serialization, as it is (may) be useful in JSON representation.

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

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助