【问题标题】:JSON tag is ignored when inserting struct/document into mongo (through mgo)将结构/文档插入 mongo 时忽略 JSON 标记(通过 mgo)
【发布时间】:2018-03-26 04:56:33
【问题描述】:

这是结构的样子 这是文件在 Mongo 中的样子。

【问题讨论】:

  • 试试bson:"fieldName"而不是json:"fieldName"
  • 不要粘贴文本图像。直接复制并粘贴文本。
  • @Luke Muller,请接受答案,或发表评论说明您无法接受答案的原因。

标签: json go mgo


【解决方案1】:

如果你查看mgo 包的文档,你会看到那里的结构用`bson:"fieldName` 而不是`json:"fieldName"` 注释。可以看一个例子here

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

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

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

【讨论】:

    【解决方案2】:

    您实际上可以同时使用json 和bson 标签。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      相关资源
      最近更新 更多