我做了一个简单的API,使用gingonic和一个mongo数据库.我将向API发布一个类似这样的简单对象,以创建具有相同形状的mongo文档.我发现了很多使用数组但不使用映射的示例.这是我在www.mongodb.com的快速入门后做的.

{
    "email": "test@example.com",
    "profile": {
        "first_name": "Test",
        "last_name": "Example"
    }
}

我有这两个GO struct (用于User和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"`
}

这是我的创建函数:

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
}

它将创建一个文档,但如下所示(因此没有子文档配置文件):

{
    "email": "test@example.com",
    "first_name": "Test",
    "last_name": "Example"
}

在不使用Go struct 的情况下创建新文档效果很好.那么,如何使用包含子文档的GO struct 为JSON对象建模呢?我找不到太多的例子,甚至在GitHub上也找不到.有谁能给我指个方向吗?

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},
     }},
}

推荐答案

您使用了bson:"profile,inline"标记,告诉它内联,这就是数据库中没有子文档的原因.它完全按照你的要求go 做.

如果您不想内联配置文件但有一个子文档,请删除,inline选项:

Profile *Profile `json:"profile" binding:"required" bson:"profile"`

Mongodb相关问答推荐

MongoDB(Mongoose)条件判断没有像我预期的那样工作

spring-data-mongodb 上的 TopN 聚合

我可以在 MongoDB 中将字段值设置为对象键吗?

随着时间的推移在 mongodb 中获得

定期自动轮换 MongoDb 集合

如何使用指南针连接到 mongodb replicaset (k8s)

分页时根据唯一字段mongodb获取数据

(MongoDB)在同一管道中结合联合和交集

如何在 MongoDB 中已经存在的 slug 中添加一个随机数?

MongoDb 聚合未正确分组

mongoose中的 required是什么意思?

在 Heroku 上使用 Node 读取、写入和存储 JSON

带有 mongodb 和 nodejs 的实时 Web 应用程序

Mongoose 的保存回调是如何工作的?

MongoDB 批处理操作的最大大小是多少?

Mongodb Atlas:管理员未授权执行命令

将新值推送到 mongodb 内部数组 - mongodb/php

无法在 mac os 10.9 上安装 mongodb php 驱动程序

如何从mongoose中的对象 ID 获取创建日期?

有没有办法执行更新操作的dry run?