Golang 导入的字段与标准字段声明的行为不同

Golang imported fields do not act the same as standard field declarations

我将尝试简化问题,而不是将整个项目纳入范围,因此如果您有任何疑问,我会尝试更新更多信息。

我正在使用 3 个结构:

type Ticket struct{
  ID bson.ObjectID `json:"id" bson:"_id"`
  InteractionIDs []bson.ObjectId `json:"interactionIds" bson:"interactionIds"`
  TicketNumber int `json:"ticketNumber" bson:"ticketNumber"`
  Active bool `json:"active" bson:"active"`
  // Other fields not included
}

type TicketInteraction struct{
  ID bson.ObjectID `json:"id" bson:"_id"`
  Active bool `json:"active" bson:"active"`
  // Other fields not included
}

type TicketLookupTicket struct{
  Ticket
  Interactions []TicketInteraction `json:"interactions" bson:"interactions"`
}

然后我有一个正在使用的 mgo 管道 'join' 两个集合在一起

var tickets []TicketLookupTicket
c := mongodb.NewCollectionSession("tickets")
defer c.Close()

pipe := c.Session.Pipe(
  []bson.M{
    "$lookup": bson.M{
      "from": "ticketInteractions",
      "localField": "interactionIds",
      "foreignField": "_id",
      "as": "interactions",
    }
  },
)
pipe.All(&tickets)

现在应该使用数据库的结果填充工单,但实际发生的只是每张工单中的交互已被填充。它最终看起来像这样:

[
  {
    ID: ObjectIdHex(""),
    InteractionIDs: nil,
    TicketNumber: 0,
    Active: false,
    // Other Fields, all with default values
    Interactions: []{
      {
        ID: ObjectIdHex("5a441ffea1c9800148669cc7"),
        Active: true,
        // Other Fields, with appropriate values
      }
    }
  }
]

现在,如果我在 TicketLookupTicket 结构中手动声明一些 Ticket 结构字段,这些字段将开始填充。例如:

type TicketLookupTicket struct{
  Ticket
  ID bson.ObjectId `json:"id" bson:"_id"`
  TicketNumber int `json:"ticketNumber" bson:"ticketNumber"`
  Active bool `json:"active" bson:"active"`
  Interactions []TicketInteraction `json:"interactions" bson:"interactions"`
}

现在 ID、TicketNumber 和 Active 将开始填充,但其余字段不会。

谁能解释为什么导入的 Ticket 字段的行为与声明的字段不同?

Per the documentation,需要在字段中添加inline标签:

type TicketLookupTicket struct{
  Ticket `bson:",inline"`
  Interactions []TicketInteraction `json:"interactions" bson:"interactions"`
}

inline Inline the field, which must be a struct or a map. Inlined structs are handled as if its fields were part of the outer struct. An inlined map causes keys that do not match any other struct field to be inserted in the map rather than being discarded as usual.

默认情况下,它假定嵌入字段 Ticket 应由 TicketLookupTicket.Ticket 处的对象填充。