首页 文章

使用带golang的mgo无法检索“_id”值

提问于
浏览
19

这是我的结构定义:

type Article struct {
    Id      bson.ObjectId `json:"id"        bson:"_id,omitempty"`
    Title   string        `json:"title"`
    Author  string        `json:"author"`
    Date    string        `json:"date"`
    Tags    string        `json:"tags"`
    Content string        `json:"content"`
    Status  string        `json:"status"`
}

这是我从数据库中获取数据的方法:

func AllArticles() []Article {
    articles := []Article{}
    err := c_articles.Find(bson.M{}).All(&articles)
    if err != nil {
        panic(err)
    }

    return articles
}

这是存储在数据库中的一个对象:

{ "_id" : ObjectId( "5281b83afbb7f35cb62d0834" ),
  "title" : "Hello1",
  "author" : "DYZ",
  "date" : "2013-11-10",
  "tags" : "abc",
  "content" : "This is another content.",
  "status" : "published" }

这是打印结果:

[{ObjectIdHex("") Hello1 DYZ 2013-11-10 abc This is another content. published}     {ObjectIdHex("") Hello2 DYZ 2013-11-14 abc This is the content. published}]

看来我无法获得 _id 字段的实际值,它始终是 "" . 有什么问题?

3 回答

  • 34

    我发现了这个问题 .

    在代码中:

    Id      bson.ObjectId `json:"id"        bson:"_id,omitempty"`
    

    json:bson: 之间,我使用 tab 而不是 space ,因此出现问题 . 如果我将这行代码更改为:

    Id      bson.ObjectId `json:"id" bson:"_id,omitempty"`
    

    json:bson: 之间的 one space ,结果很好 .

  • 3

    我有同样的问题,并且能够弄清楚我的进口混乱了 . 我有一种感觉,Gustavo无法重现这个问题,因为你没有包括你的进口看起来像什么,他正确地填写了它们 .

    只是简单解释我的问题是如何相似的:

    这个 -

    err := db.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(&user)
    

    我没有为我工作,它不会从数据库中获取信息并将返回 -

    {ObjectIdHex("")    }
    

    我是如何修理的......我们发现了

    在server.go页面中,其中一个导入就是这个 .

    "gopkg.in/mgo.v2”
    

    应该是这样的 .

    "labix.org/v2/mgo”
    

    真正的错误不是使用gopkg.in/mgo.v2 . 代码是混合labix.org/和gopkg.in导入模块 .

    所以诀窍是使用它 .

    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson”
    

    或这个 .

    "labix.org/v2/mgo"
    "labix.org/v2/mgo/bson”
    

    但不要混合它们 . 最好的一个是首选的,因为这是最新的文档使用的 .

    希望这可以帮助 .

  • 9

    你的代码很好 .

    这是一个自包含的示例,其中包含您未经修改的代码:

    这是输出:

    "R\x94\xa4J\xff&\xc61\xc7\xfd%\xcc" "Some Title"
    

    问题出在其他地方 . 例如,该集合可能实际上没有 _id 字段 .

相关问题