无法将 mongo 文档 ID 解码到结构字段

Fail to decode mongo document ID onto struct field

正在尝试使用 mongo go driver to decode a fetch a single user document and decode it into a struct, using the findOne 方法。但是,我无法解码结构字段上的文档 ID。我尝试在他们的示例或其他 sites/blogs 中寻找它,但没有成功。我正在与:

下面是代码片段:

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

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

结构应该是这样的:

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

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

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

see more on Github