DEV Community

Discussion on: MongoDB Golang Driver Tutorial

Collapse
 
findridoy profile image
findridoy

type Hero struct {
Name string json:"name"
Alias string json:"alias"
Signed bool json:"signed"
}

Why i need this json:name, json:alias, json signed with my struct value?

Collapse
 
eduardohitek profile image
Eduardo Hitek

Hi frindidoy, great question!

It's true that you don't need to add this tags on your Struct, but I do for 2 mainly reasons:

  1. Almost all of my code is form REST/Http Request, so I need to decode the Request's body into a Struck, and having theses tags make the process automatic to me.
  2. And for me is more like a kind of documentation, because I know the fields names in the database so when I look to my Struct it gives me a smallprint of how my data is organized.

One curious thing is, if you use the bson: tag. You don't need to obey the order and neither the names between the Struct and you Collection.

type Hero struct {
    MyVar1 bool   `json:"signed" bson:"signed"`
    MyVar2 string `json:"alias" bson:"alias"`
    MyVar3 string `json:"name" bson:"name"`
}

Let me know if you still have any doubts about it!