英文:
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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论