doubei2231 2019-03-31 21:02
浏览 580
已采纳

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

I am using the MongoDb Go Driver and I am unable to get the ObjectId subvalue from the JSON decoded in my structs.

Note: I am using a different library/API than this question, so please don't mark this as duplicate.

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"
)

I have a type of struct like this for processing the results

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"`    
}

And then I go to retrieve the contacts like this:

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)

The subfields for "health" appear exactly as they should, but for some reason the subfield from the "_id" part of the results is nowhere to be found. Can anyone help me with this??

The JSON response from the database comes out like this, and for some reason I am able to get the subfields for the health field, but not the _id field. Why not?

Raw JSON response of DB

[{
    "_id": { 
        "$obj": "5c601648ae25e40e2631c3ef" 
    }, 
    "name": "Bob Smith", 
    "email": "bob@smith.com", 
    "health": { 
        "height": 192, 
        "weight": 85 
    }
}]

fmt.Println's output of the decoded contacts array:

[{{} Bob Smith bob@smith.com {192 85}}]
  • 写回答

2条回答 默认 最新

  • duandanai6470 2019-03-31 23:20
    关注

    Thanks to this excellent tutorial and this anwser I was able to find the answer.

    I needed to set the ID in my struct as a primitive.ObjectID, and made sure I had imported "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"`    
    }
    

    For those looking to use the official MongoDB Go driver, see this tutorial below provides very good explanation and examples of how to do all the CRUD operations necessary for a basic REST api etc.

    Using the official MongoDB Go driver

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀