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

2024-01-13

我正在使用MongoDb Go 驱动程序 https://github.com/mongodb/mongo-go-drive我无法从结构中解码的 JSON 中获取 ObjectId 子值。

Note:我使用的库/API 与这个问题 https://stackoverflow.com/questions/47712710/cant-get-mongodb-record-by-objectid-in-golang,所以请不要将其标记为重复。

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": "[email protected] /cdn-cgi/l/email-protection", 
    "health": { 
        "height": 192, 
        "weight": 85 
    }
}]

fmt.Println解码后的输出contacts大批:

[{{} Bob Smith [email protected] /cdn-cgi/l/email-protection {192 85}}]

谢谢这个优秀的教程 https://vkt.sh/go-mongodb-driver-cookbook/ and 这个答案 https://stackoverflow.com/a/54116108/8620945我找到了答案。

我需要设置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"`    
}

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

使用官方 MongoDB Go 驱动程序 https://vkt.sh/go-mongodb-driver-cookbook/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Golang 中无法从 MongoDB 结果解码 ObjectId SubValue 的相关文章

随机推荐