Search code examples
mongodbgomgoobjectid

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


Solution

  • 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