duandang6111 2019-08-01 08:44
浏览 111
已采纳

mongodb ObjectId的问题

I have Go code that connects to a mongodb database. The problem is that when I'm trying to get a record from the collection there is an "_id" field of the ObjectId type, but in the mgo driver ObjectId is

type ObjectID [12]byte

but when I'm trying to get record Go says:

reflect.Set: value of type []uint8 is not assignable to type ObjectID

I have tried to create my own []uint8 type but I have no idea how to convert []uint8 ("ObjectId") to string or to find some record by those ids.

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

  • 写回答

1条回答 默认 最新

  • douyuan4697 2019-08-01 09:05
    关注

    You have to use the "predefined" bson.ObjectId to model values of MongoDB's ObjectId:

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

    And when you query an object by ID whose type is MongoDB's ObjectId, use a value of type bson.ObjectId. And you may use the Collection.FindId() method:

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

    See details here: Find by id with mgo; and MongoDB slice query into golang

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料