登录
首页 >  Golang >  Go问答

与 MongoDB go 客户端一起使用时 bson struct 标签的必要性

来源:stackoverflow

时间:2024-04-29 12:06:34 199浏览 收藏

你在学习Golang相关的知识吗?本文《与 MongoDB go 客户端一起使用时 bson struct 标签的必要性》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我正在观看一篇关于如何创建使用 mongodb 进行持久化的 go restful api 的教程(更准确地说是这个)。

讲师在他的模型(结构)中使用两者 jsonbson 标签,类似于

type NoteUpdate struct {
    ID        string `json:"id,omitempty" bson:"_id,omitempty"`
    Title     string `json:"title" bson:"title,omitempty"`
    Content   string `json:"content" bson:"content,omitempty"`
    ChangedAt int64  `json:"changed_at" bson:"changed_at"`
}

但是官方的 go 驱动程序示例并没有这样做。

事实上,根本没有使用任何结构标签。

使用 bson 标签的目的/用处是什么?

我想到的一件事是,人们想要创建自定义 mongo _id 字段,在这种情况下,应该声明与该结构体字段的显式 bson 映射。

bson 标签还有其他附加值吗?


解决方案


mongodb 驱动程序仅使用 bson 标签。 json 标签仅适用于 encoding/json 包(或处理 json 编组/解组的其他 3rd 方包)。

您不需要指定和使用 bson 标记,在这种情况下,驱动程序在编码结构值时通常只使用小写字段名称。但是,当您需要不同的名称时,需要 bson 标签。

即使您想使用小写的字段名称,指定 bson 标记也是一个好习惯,因为有时您可能需要重命名结构字段,这会导致麻烦和不一致。如果您指定 bson 标记,那么将来重命名字段也没关系,它们仍然会编组到相同的属性中,并且解组它们将继续工作。

bson 标记还可以包含 flags更改默认封送行为:

OmitEmpty  Only include the field if it's not set to the zero value for the type or to
           empty slices or maps.

MinSize    Marshal an integer of a type larger than 32 bits value as an int32, if that's
           feasible while preserving the numeric value.

Truncate   When unmarshaling a BSON double, it is permitted to lose precision to fit within
           a float32.

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.

Skip       This struct field should be skipped. This is usually denoted by parsing a "-"
           for the name.

终于介绍完啦!小伙伴们,这篇关于《与 MongoDB go 客户端一起使用时 bson struct 标签的必要性》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>