【发布时间】:2019-08-22 01:08:16
【问题描述】:
我正在使用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}}]
【问题讨论】: