douzhi3586 2017-12-17 21:19
浏览 90
已采纳

如何使用bson.ObjectId字段正确解组mgo结果到结构中

I'm using the mgo package for Mongo database interactions.

I currently have a base struct that looks like:

type Document struct {
    ID bson.ObjectId `bson:"_id"` // Unique document _id.

    EntityId bson.ObjectId `bson:"entity_id"` // Used to create relationships between collections.

    EffectiveDate time.Time `bson:"effective_date"` // Date this document becomes effective.

    // Audit Fields.
    CreatedAt time.Time     `bson:"created_at"`
    CreatedBy bson.ObjectId `bson:"created_by"`

    UpdatedAt time.Time     `bson:"updated_at"`
    UpdatedBy bson.ObjectId `bson:"updated_by"`

    // Document state(stale, current, etc..)
    IsActive  bool `bson:"is_active"`
    IsDeleted bool `bson:"is_deleted"`
    IsMaster  bool `bson:"is_master"`

    ExternalID string `bson:"external_id"`

    CompanyID bson.ObjectId `bson:"company_id"` // The unique ObjectId for that company.
}

I embedded this Document struct into more specific collection defined structs that look like:

// Represents a product-category document.
type ProductCategory struct {
    Document // Embedded base document struct contains all base fields.

    Name       string `bson:"name"`        // Name of the category
    CategoryID string `bson:"category_id"` // Unique id of the category.
}

I'm able to run queries like this one below and get all the fields I need besides the bson.ObjectId fields including ID(_id).

  var pc collections.ProductCategory
    col := session.DB("some_db").C("product-category")

    col.Find(nil).One(&pc)

    // All fields are here besides [Id, CompanyId, CreatedBy, UpdatedBy] etc..

Is there any glaring issues on why the Fields I need aren't being added to the struct?

  • 写回答

1条回答 默认 最新

  • douduan4116 2017-12-17 21:39
    关注

    You need to use the inline flag:

    type ProductCategory struct {
        Document `bson:",inline"`
        // other fields ...
    }
    

    See the bson Marshal docs for more info:

    inline     Inline the field, which must be a struct or a map,
               causing all of its fields or keys to be processed as if
               they were part of the outer struct. For maps, keys must
               not conflict with the bson keys of other struct fields.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?