本文介绍了与MongoDB go client一起使用时bson struct标签的必要性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在观看有关如何创建使用MongoDB进行持久化的Go静态API的教程(一个更精确).

I am watching a tutorial on how to create Go restful APIs that use MongoDB for persistence (this one to be more precise).

讲师在其模型(结构)中使用了两者 json bson 标签,例如

The instructor is using in his model (struct) both json and bson tags, something like

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 driver 示例不起作用如此.

However the official go driver example does not do so.

事实上,根本没有使用struct标记.

As a matter of fact there, no struct tags are used at all.

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

What is the purpose / usefulness of using bson tags?

我想到的一件事是,一个人想要创建自定义mongo _id 字段,在这种情况下,应该使用该结构字段的显式 bson 映射被宣布.

The one thing that comes to my mind is the case were one would want to create custom mongo _id fields in which case an explicit bson mapping with that struct's field should be declared.

bson标签是否还有其他附加值?

Is there any other added value for the bson tags?

推荐答案

MongoDB驱动程序仅使用 bson 标记. json 标签仅用于 encoding/json 包(或其他处理JSON封送/拆组的第三方包装).

The MongoDB drivers use only the bson tags. json tags are solely for the encoding/json package (or other 3rd party packages dealing with JSON marshaling/unmarshaling).

您不需要指定和使用 bson 标记,在这种情况下,驱动程序通常在对结构值进行编码时仅使用小写的字段名称. bson 标签是必需的,但是当您需要其他名称时.

You are not required to specify and use bson tags, in which case the drivers usually just use the lowercased field names when encoding struct values. bson tags are required however when you need a different name.

即使您要使用小写的字段名称,也最好指定 bson 标记,因为有时可能需要重命名结构字段,这会带来麻烦和不一致之处.如果指定 bson 标记,则以后再重命名字段都没关系,它们仍将编组为相同的属性,并且对它们进行编组将继续起作用.

And it's also a good practice to specify bson tags even if you want to use the lowercased field names, because there might come a time when you need to rename struct fields, and that would cause troubles and inconsistencies. If you specify bson tags, it won't matter if you rename fields in the future, they will be still marshalled into the same properties, and unmarshaling them will continue to work.

这篇关于与MongoDB go client一起使用时bson struct标签的必要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 12:21