【问题标题】:Fail to decode mongo document ID onto struct field无法将 mongo 文档 ID 解码到 struct 字段
【发布时间】:2020-04-02 01:16:48
【问题描述】:

尝试使用mongo go driver 解码获取单个用户文档并将其解码为结构,使用findOne 方法。但是,我无法解码 struct 字段上的文档 ID。我尝试在他们的示例或其他网站/博客中寻找它,但没有运气。我正在与:

  • 转到 v1.13.4
  • mongo v4.2.1
  • mongo-go-driver v1.1.3

下面是代码sn-p:

type User struct {
    ID            interface{} `json:"_id"`
    Name          string
    Email         string
    Password      string // hashed
}

/* Other versions of User struct which I already tried

type User struct {
    ID            interface{}
    Name          string
    Email         string
    Password      string // hashed
}

type User struct {
    ID            string `json:"_id"`
    Name          string
    Email         string
    Password      string // hashed
}

type User struct {
    ID            string
    Name          string
    Email         string
    Password      string // hashed
}
*/

func main() {
    conn := service.MongoConn() // get a mongo connection on the required database
    user := &service.User{}
    err := conn.Collection("users").
             FindOne(context.Background(), bson.M{"email": "foo@bar.com"}).
             Decode(user)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", user)
}

我想在不同集合中的其他文档中使用 doc ID 作为参考,否则,我必须求助于其他一些独特的字段,例如电子邮件。

【问题讨论】:

  • 您是否尝试过使用 bson:"_id" 而不是 json:"_id" 标记字段?

标签: mongodb go struct decode


【解决方案1】:

结构应该是这样的:

import "go.mongodb.org/mongo-driver/bson/primitive"

type User struct {
    ID primitive.ObjectID `bson:"_id"`
    ...
}

要将您的_id 转换为字符串,请使用xx.ID.Hex()

see more on Github

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多