2017-12-17 5 views
0

Mongoデータベースの操作にmgoパッケージを使用しています。私は、クエリを実行することができるよmsoの結果をbson.ObjectIdで構造体に正しくアンマーシャリングする方法

// 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. 
} 

:私は次のようになり、より具体的なコレクション定義された構造体には、このドキュメントの構造体を組み込み

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

は、私は現在のように見える基本構造体を持っていますこれを以下のようにして、ID(_id)を含むbson.ObjectIdフィールドのほかに必要なすべてのフィールドを取得します。

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.. 

私が必要とするフィールドが構造体に追加されていない理由は何ですか?

+1

[MgOをして、ネストされた構造体の保存]の可能複製(https://stackoverflow.com/questions/20849591/stored-nested-structs-with-mgo) – Marc

答えて

1

あなたはinlineフラグを使用する必要があります。

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

は、詳細はbson Marshal docsを参照してください:

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. 
関連する問題