我正在使用 MongoDb Go Driver并且我无法从在我的结构中解码的 JSON 中获取 ObjectId 子值。
注意:我使用的库/API 不同于 this question , 所以请不要将其标记为重复。
import (
"net/http"
"github.com/go-chi/chi"
"encoding/json"
"time"
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"fmt"
)
我有这样一种结构来处理结果
type Contact struct {
Id struct {
ObjId string `json:"$oid"`
} `json:"_id"`
Name string `json:"name"`
Email string `json:"email"`
Health struct {
Weight int `json:"weight"`
Height int `json:"height"`
} `json:"health"`
}
然后我去像这样检索联系人:
var contacts []Contact
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
cursor, err := collection.Find(ctx, bson.M{})
if err != nil {
panic(err)
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var contact Contact
fmt.Println(cursor)
cursor.Decode(&contact)
contacts = append(contacts, contact)
}
if err := cursor.Err(); err != nil {
panic(err)
}
// I want to do more with the contacts, but .Id is empty :-(
fmt.Println(contacts)
"health"
的子字段完全按照它们应有的方式出现,但由于某种原因,结果的 "_id"
部分的子字段无处可寻 谁能帮我解决这个问题??
来自数据库的 JSON 响应是这样的,出于某种原因,我能够获取 health
字段的子字段,但不能获取 _id
字段。为什么不?
数据库的原始 JSON 响应
[{
"_id": {
"$obj": "5c601648ae25e40e2631c3ef"
},
"name": "Bob Smith",
"email": "bob@smith.com",
"health": {
"height": 192,
"weight": 85
}
}]
fmt.Println
解码后的 contacts
数组的输出:
[{{} Bob Smith bob@smith.com {192 85}}]
最佳答案
感谢this excellent tutorial和 this anwser我能够找到答案。
我需要在我的结构中将 ID
设置为 primitive.ObjectID
,并确保我已导入 "go.mongodb.org/mongo-驱动程序/bson/原语”
type Contact struct {
ID primitive.ObjectID `json:"_id" bson:"_id"
Name string `json:"name" bson:"name"`
Email string `json:"email" bson:"email"`
Health struct {
Weight int `json:"weight" bson:"weight"`
Height int `json:"height" bson:"height"`
} `json:"health" bson:"health"`
}
对于那些希望使用官方 MongoDB Go 驱动程序的人,请参阅下面的教程,其中提供了非常好的解释和示例,说明如何执行基本 REST api 等所需的所有 CRUD 操作。
关于mongodb - 无法从 MongoDB 中解码 ObjectId SubValue 结果在 Golang 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445429/