如何使用bson.ObjectId字段

时间:2017-12-17 21:19:04

标签: mongodb go

我正在使用mgo包进行Mongo数据库交互。

我目前有一个基本结构,如下所示:

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

我将此Document结构嵌入到更具体的集合定义的结构中,如下所示:

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

我可以运行下面这样的查询,除了包含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 个答案:

答案 0 :(得分: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.