【问题标题】:Avoid nested struct as nested value in go-mongo避免嵌套结构作为 go-mongo 中的嵌套值
【发布时间】:2021-09-29 20:24:14
【问题描述】:

我对所有其他结构都有这个通用结构。

// Base 包含所有文档的公共字段,如下所示。

type Base struct {
    CreatedAt time.Time `json:"createdAt"  bson:"created_at"`
    UpdatedAt time.Time `json:"updatedAt" bson:"updated_at"`
    DeletedAt time.Time `json:"deletedAt,omitempty" bson:"deleted_at"`
}

type Nice struct {
    Base
    Notes             string             `json:"notes" bson:"notes"`
}

现在的问题是 go-Mongo 将其保存为具有以下名称的嵌套对象,我想避免将其保存为嵌套对象。有什么方法可以避免它,我在文档中找不到任何东西

{ "_id" : ObjectId("6154807677b7f58b6438b71c"), "base" : { "created_at" : ISODate("2021-09-29T15:04:22.322Z"), "updated_at" : ISODate("0001-01-01T00:00:00Z"), "deleted_at" : ISODate("0001-01-01T00:00:00Z") } "notes" : ""}

【问题讨论】:

    标签: go mongo-go mongo-go-driver


    【解决方案1】:

    在 bson 文档中:

    内联:如果为结构或映射字段指定了内联结构标记,则该字段将在编组时“扁平化”,而在解组时“未扁平化”。

    所以使用:

    type Nice struct {
        Base `bson:",inline"`
        Notes             string             `json:"notes" bson:"notes"`
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 2019-03-24
      • 2011-02-16
      相关资源
      最近更新 更多