将struct / document插入mongo时会忽略JSON标记(通过mgo)

时间:2017-10-14 02:49:27

标签: json go mgo

这就是结构的样子 enter image description here 这就是Mongo中文档的样子。 enter image description here

2 个答案:

答案 0 :(得分:3)

如果您查看mgo包的文档,您会看到其中的`bson:"fieldName`而非`json:"fieldName"`注释的结构。您可以看到示例here

原因是mongo使用bson序列化格式而不是json来通过网络发送结构。 bsonjson非常相似,但它是一种二进制格式,并且针对数据库等存储系统进行了优化。

所以更新你的结构看起来像这样:

type Event struct {
    Id           string     `bson:"id"`
    CreationDate time.Time  `bson:"creationTime"`
    CreatorId    string     `bson:"creatorId"`
    Place        string     `bson:"place"`
    ActivityId   string     `bson:"activityId"`
    Time         time.Time  `bson:"time"`
    Lang         string     `bson:"lang"`
}

答案 1 :(得分:0)

您实际上可以同时使用jsonbson标记。

type Event struct {
    Id           string    `json:"id" bson:"id"`
    CreationDate time.Time `json:"creationTime" bson:"creationTime"`
    CreatorId    string    `json:"creatorId" bson:"creatorId"`
    Place        string    `json:"place" bson:"place"`
    ActivityId   string    `json:"activityId" bson:"activityId"`
    Time         time.Time `json:"time" bson:"time"`
    Lang         string    `json:"lang" bson:"lang"`
}