gpt4 book ai didi

mongodb - 无法使用带有 golang 的 mgo 检索 "_id"值

转载 作者:IT老高 更新时间:2023-10-28 13:02:29 25 4
gpt4 key购买 nike

这是我的结构定义:

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 字段的真实值,它始终是 ""。有什么问题?

最佳答案

我找到了问题。

在代码中:

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

json:bson: 之间,我使用了 tab 而不是 space 所以问题就出现了。如果我将这行代码更改为:

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

json:bson: 之间使用 one space,结果证明可以正常工作。

关于mongodb - 无法使用带有 golang 的 mgo 检索 "_id"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20215510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com