在 Golang 中使用 mgo 包无法获取 mongodb 中对象的 "_id" 字段

 mobiledu2502876847 发布于 2022-10-25 09:58

这是我的结构体:

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

这是我获取 mongodb 中数据的函数:

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

这是打印结果:

[{ObjectIdHex("") Hello1 DYZ 2013-11-10 abc This is another content. published} {ObjectIdHex("") Hello2 DYZ 2013-11-14 abc This is the content. published} {ObjectIdHex("") Hello3 DYZ 2013-11-15 abc This is the content haven't been published. draft}]

可以看到,对应_id的值是ObjectIdHex(""),但是在数据库中的数据是这样的:

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

即使我把筛选条件变成:

err := c_articles.Find(bson.M{"_id": bson.ObjectIdHex("5281b83afbb7f35cb62d0834")}).All(&articles)

打印出来的数据仍然是上面那样,没有值。这是为什么?

3 个回答
  • Id bson.ObjectId json:"id" bson:"_id"

    json和bson之间的空格是否用了tab?

    2022-10-26 23:05 回答
  • 在so中找到原因了

    windows和unix仓库提交网址不一致
    stockoverflow上的解释

    2022-10-26 23:05 回答
  • docker login --username=youruser --password=yourpassword --email=youremail https://index.docker.io/v1/

    具体可以看上面柳月给的网址或者:https://github.com/docker/hub-feedback/issues/473

    2022-10-26 23:05 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有