无法使用mgo检索包含大写字母的键的值。

huangapple go评论82阅读模式
英文:

Can not retrieve value using mgo when the key contains uppercase

问题

从mongoDB中获取的数据如下:

{
    "_id" : ObjectId("5536def4e4b0644323e219a8"),
    "title" : "The Title",
    "description" : "The Description",
    "timeStamp" : "21/04/2015",
    "category" : "news",
    "url" : "http://www.example.com",
    "source" : "Evening Times",
    "mainStory" : "This is the main story."
}

在我的代码中,结构如下:

type NewsData struct {
    Title       string `bson:"title" json:"title"`
    TimeStamp   string `bson:"timeStamp" json:"timeStamp"`
    Description string `bson:"description" json:"description"`
    MainStory   string `bson:"mainStory" json:"mainStory"`
}

然后我使用以下代码提取信息:

err = conn.Find(nil).Select(bson.M{"title": 1, "timeStamp": 1, "description": 1, "mainStory": 1}).All(&result)

然而,当我打印result时,timeStampmainStory的值为空。我检查了文档,它说mgo将键视为小写,所以当mongoDB中的键包含大写字母时,会出现问题。

如何解决这个问题?

英文:

One data from mongoDB is

{
    "_id" : ObjectId("5536def4e4b0644323e219a8"),
    "title" : "The Title",
    "description" : "The Description",
    "timeStamp" : "21/04/2015",
    "category" : "news",
    "url" : "http://www.example.com",
    "source" : "Evening Times",
    "mainStory" : "This is the main story."
}

In my code, the structure is

type NewsData struct {
    Title       string `bson: "title" json: "title"`
    TimeStamp   string `bson: "timeStamp" json: "timeStamp"`
    Description string `bson: "description" json: "description"`
    MainStory   string `bson: "mainStory" json:"mainStory"`
}

Then I use the following code to extract information

err = conn.Find(nil).Select(bson.M{"title": 1, "timeStamp": 1, "description": 1, "mainStory": 1}).All(&result)

However, when I print result out, the value of timeStamp and mainStory is empty. I checked the documents, it says that mgo take the key as lowercase, so when the key in mongoDB contains uppercase, it would be a problem.

How can I fix this problem?

答案1

得分: 1

字段标签中存在语法错误。在字段标签中的冒号(:)和引号(")之间删除空格。

TimeStamp   string `bson:"timeStamp" json:"timeStamp"`

字段标签的语法是严格的。

除此之外,你可能应该在结构体中添加

ID bson.ObjectId `bson:"_id"`

以便应用程序可以访问对象ID。

英文:

There is a syntax error in the field tag. Remove the space between the ':' and the '"' in the field tag.

TimeStamp   string `bson:"timeStamp" json:"timeStamp"`

The syntax for field tags is unforgiving.

Separate from this issue, you should probably add

ID bson.ObjectId `bson:"_id"` 

to the struct the application can access the object id.

huangapple
  • 本文由 发表于 2015年7月1日 07:51:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/31150418.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定