如何使用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?

douhuitan5863
douhuitan5863 使用mgo存储嵌套结构的可能重复项
2 年多之前 回复

1个回答



您需要使用 inline </ code>标志:</ p>

 类型ProductCategory struct {
Documentbson:“,inline”
//其他字段...
}
</ code> </ pre>

请参见 bson Marshal文档以获取更多信息:</ p>

  inline内联字段,该字段必须是结构或映射,
导致对其所有字段或键进行处理,就好像它们是外部结构的一部分。 对于地图,键不得与其他结构字段的bson键冲突。
</ code> </ pre>
</ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐