如何创建一个 Mongo 文档,在两个结构体之后对其进行建模?

问题描述 投票:0回答:1

我使用 gingonic 和 mongo 数据库制作了一个简单的 api。我将一个像这样的简单对象发布到 api,以创建具有相同形状的 mongo 文档。我发现很多使用数组的例子,但没有使用地图。我是按照 www.mongodb.com 上的快速入门制作的。

{
    "email": "[email protected]",
    "profile": {
        "first_name": "Test",
        "last_name": "Example"
    }
}```

And I have these two go structs (for user and profile)

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

And this is my create 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 without the subdocument profile):

```{
    "email": "[email protected]",
    "first_name": "Test",
    "last_name": "Example"
}```


Creating a new document without go structs works fine. So how do I model a json object using go structs containing subdocuments? I couldn't find much examples, not even on github. Anybody 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},
     }},
}```
json mongodb go struct mongo-go
1个回答
0
投票

您使用了

bson:"profile,inline"
标签,告诉它内联,这就是您的数据库中没有子文档的原因。它完全按照您的要求做。

如果您不想内联配置文件但有子文档,请删除

,inline
选项:

Profile *Profile `json:"profile" binding:"required" bson:"profile"`
© www.soinside.com 2019 - 2024. All rights reserved.