Necessity of bson struct tag when using with MongoDB go client

本小妞迷上赌 提交于 2021-02-11 15:31:40

问题


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

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

However the official go driver example does not do so.

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

What is the purpose / usefulness of using bson tags?

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.

Is there any other added value for the bson tags?


回答1:


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).

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.

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.




回答2:


bson tags can also contain flags to change the default marshaling behavior:

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.


来源:https://stackoverflow.com/questions/59561529/necessity-of-bson-struct-tag-when-using-with-mongodb-go-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!