Home >Backend Development >Golang >How to create a Mongo document that models it after two structures?
php editor Baicao will introduce you in this article how to create a document in a Mongo database and model it between two different structures. In the Mongo database, a document is a basic unit used to store and organize data, similar to a row or document in a relational database. In order to make better use of Mongo's flexibility and scalability, we can plan and design the structure of the document to meet our specific needs before creating it. Next, we'll detail how to create a Mongo document and model it between different structures.
I made a simple api using gingonic and mongo database. I post a simple object like this to the api to create a mongo document with the same shape. I found a lot of examples using arrays, but not maps. I did this by following the quickstart at www.mongodb.com.
{ "email": "[email protected]", "profile": { "first_name": "Test", "last_name": "Example" } }
I have these two go structures (for user and config files)
type User struct { ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"` Email string `json:"email" binding:"required,email" bson:"email"` Profile *Profile `json:"profile" binding:"required" bson:"profile,inline"` } type Profile struct { FirstName string `json:"first_name" binding:"required,min=3" bson:"first_name"` LastName string `json:"last_name" binding:"required" bson:"last_name"` }
This is my creation function:
func (dbc *Dbc) CreateUser(user *models.User) error { newUser := models.User{ Email: user.Email, Profile: &models.Profile{ FirstName: user.Profile.FirstName, LastName: user.Profile.LastName}, } _, err := dbc.GetUserCollection().InsertOne(dbc.ctx, newUser) return err }
It will create a document, but like this (so no subdocument profiles):
{ "email": "[email protected]", "first_name": "Test", "last_name": "Example" }
Creating new documents without go structures works fine. So how to model a json object using a go structure containing subdocuments? I can't find many examples, not even on github. Anyone want to point me in the right direction?
newUser := bson.D{ bson.E{Key: "email", Value: user.Email}, bson.E{Key: "profile", Value: bson.D{ bson.E{Key: "first_name", Value: user.Profile.FirstName}, bson.E{Key: "last_name", Value: user.Profile.LastName}, }}, }
You used the bson:"profile,inline"
tag to tell it to inline, which is why you don't have the subdocument in your database. It does exactly what you ask it to do.
If you don't want to inline the configuration file but have subdocuments, remove the ,inline
option:
Profile *Profile `json:"profile" binding:"required" bson:"profile"`
The above is the detailed content of How to create a Mongo document that models it after two structures?. For more information, please follow other related articles on the PHP Chinese website!