首页 > 解决方案 > mongodb ObjectId 的问题

问题描述

我有连接到 mongodb 数据库的 Go 代码。问题是,当我试图从集合中获取记录时,有一个ObjectId类型为“_id”的字段,但在 mgo 驱动程序ObjectId中是

type ObjectID [12]byte

但是当我试图获得记录时,Go 说:

reflect.Set:[]uint8 类型的值不可分配给 ObjectID 类型

我试图创建自己的[]uint8类型,但我不知道如何将[]uint8(“ObjectId”)转换为string或通过这些 id 找到一些记录。

// ObjectId type that mongodb wants to see
type ObjectID []uint8

// model
type Edge struct {
    ID          ObjectID `bson:"_id"`
    Name        string   `bson:"name"`
    StartVertex string   `bson:"startVertex"`
    EndVertex   string   `bson:"endVertex"`
}


// method for getting record by those id
session, err := mgo.Dial(config.DatabaseURL)
    if err != nil {
        fmt.Printf("Error is: %s", err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)

    //edges collection
    e := session.DB(config.DatabaseName).C(config.EdgesCollection)

    var result models.Edge

    err = e.Find(bson.M{"_id": fmt.Sprintln("ObjectId('", id, "')")}).One(&result)
    if err != nil {
        fmt.Println("Error is: ", err)
    }

标签: mongodbgomgoobjectid

解决方案


您必须使用“预定义”bson.ObjectId来模拟 MongoDB 的 ObjectId 的值:

type Edge struct {
    ID          bson.ObjectId `bson:"_id"`
    Name        string        `bson:"name"`
    StartVertex string        `bson:"startVertex"`
    EndVertex   string        `bson:"endVertex"`
}

当您通过 ID 查询类型为 MongoDB 的 ObjectId 的对象时,请使用 type 的值bson.ObjectId。您可以使用以下Collection.FindId()方法:

var id bson.ObjectId = ...
err = e.FindId(id).One(&result)

在此处查看详细信息:使用 mgo 按 id 查找;和MongoDB 切片查询到 golang


推荐阅读