如何使用bson.ObjectId字段将mgo结果正确解组为struct

问题描述 投票:1回答:1

我正在使用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.
}

我可以运行下面这样的查询,除了bson.ObjectId字段(包括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..

为什么我需要的字段没有被添加到结构中,是否有任何明显的问题?

mongodb go
1个回答
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.
© www.soinside.com 2019 - 2024. All rights reserved.