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 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法