避免在go-mongo中将嵌套结构作为嵌套值使用。

huangapple go评论75阅读模式
英文:

Avoid nested struct as nested value in go-mongo

问题

我有一个通用的结构体,用于所有其他结构体。

// 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 将其保存为嵌套对象,名称为 base,如下所示,我想避免将其保存为嵌套对象。有什么方法可以避免这种情况,我在文档中找不到任何信息。

{ "_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" : ""}
英文:

I have this common struct for all other structs.

// Base contains common fields for all documents as given below.

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"`
}

Now issue is go-Mongo save it as nested object with name base as follows and I want to avoid it to save it as nested object. What is the way to avoid it, I am unable to find anything in documentation

{ "_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" : ""}

答案1

得分: 3

这是bson文档中的内容:

> inline:如果为结构体或映射字段指定了inline结构标签,则在编组时该字段将被“展开”,在解组时将被“还原”。

因此使用以下代码:

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

It is in bson documentation:

> inline: If the inline struct tag is specified for a struct or map field, the field will be "flattened" when marshalling and "un-flattened" when unmarshalling.

So use:

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

huangapple
  • 本文由 发表于 2021年9月30日 04:24:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/69382937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定