无法在Golang中从MongoDB结果解码ObjectId子值

Ada*_*m D 2 go mongodb

我正在使用MongoDb Go驱动程序,但无法从结构中解码的JSON中获取ObjectId子值。

注意:我使用的库/ API与此问题不同,因此请不要将其标记为重复。

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"
)
Run Code Online (Sandbox Code Playgroud)

我有一个这样的结构来处理结果

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"`    
}
Run Code Online (Sandbox Code Playgroud)

然后我去检索像这样的联系人:

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)
Run Code Online (Sandbox Code Playgroud)

的子字段"health"完全按照应有的方式显示,但是由于某种原因,"_id"找不到结果部分的子字段。谁能帮我这个??

来自数据库的JSON响应是这样产生的,由于某种原因,我能够获取该字段的子health字段,但无法获取该_id字段。为什么不?

数据库的原始JSON响应

[{
    "_id": { 
        "$obj": "5c601648ae25e40e2631c3ef" 
    }, 
    "name": "Bob Smith", 
    "email": "bob@smith.com", 
    "health": { 
        "height": 192, 
        "weight": 85 
    }
}]
Run Code Online (Sandbox Code Playgroud)

fmt.Println解码contacts数组的输出:

[{{} Bob Smith bob@smith.com {192 85}}]
Run Code Online (Sandbox Code Playgroud)

Ada*_*m D 5

多亏了这个出色的教程答案,我才能够找到答案。

我需要ID在结构中将设置为primitive.ObjectID,并确保已导入"go.mongodb.org/mongo-driver/bson/primitive"

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"`    
}
Run Code Online (Sandbox Code Playgroud)

对于那些希望使用官方MongoDB Go驱动程序的人,请参见下面的本教程,该教程提供了很好的说明和示例,说明了如何执行基本REST api等必需的所有CRUD操作。

使用官方的MongoDB Go驱动程序