Reputation: 762
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?
Upvotes: 2
Views: 1224
Reputation: 21035
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.
Upvotes: 2