【问题标题】:How to properly unmarshal mgo result into struct with bson.ObjectId Fields如何使用 bson.ObjectId 字段将 mgo 结果正确解组为结构
【发布时间】:2017-12-18 05:39:55
【问题描述】:

我正在使用 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】:

您需要使用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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多