dongtang2376 2013-11-26 11:12
浏览 52

无法在Golang中使用mgo检索“ _id”值

This is my struct definition:

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

This is the method I get my data from database:

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

    return articles
}

This is one piece of object stored in database:

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

This is the printed result:

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

It seems that I can't get the real value of _id field, it's always "". What's the problem?

  • 写回答

3条回答 默认 最新

  • douyueqing1530 2013-11-26 13:42
    关注

    Your code is fine.

    Here is a self-contained example that includes your code, unmodified:

    And here is the output:

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

    The issue is elsewhere. The collection may really not have an _id field, for example.

    评论

报告相同问题?

悬赏问题

  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo