Why can't I find id using mgo golang library?
I am using mgo library for mongo operationg in golang and here is my code:
session.SetMode(mgo.Monotonic, true)
coll := session.DB("aaaw_web").C("cron_emails")
var result Result
fmt.Printf("%v", message.ID)
err = coll.FindId(bson.ObjectId(message.ID)).One(&result)
fmt.Printf("%v", result)
fmt.Println(err)
I am getting this output:
595f2c1a6edcba0619073263
{ObjectIdHex("") 0 0 0 0 { 0 false 0 } 0 0 0 0 0 0 0}
ObjectIDs must be exactly 12 bytes long (got 24)
not found
But I have verified that the document exists in mongo but fails, no idea what I am missing ...
source to share
As the error message hints, the object ID is exactly 12 bytes (12 data bytes). The 24 char long identifier you see printed is a 12 byte hex representation of the identifier (1 byte => 2 hex digits).
Use a function bson.ObjectIdHex()
to get the value bson.ObjectId
if hexadecimal representation is available.
err = coll.FindId(bson.ObjectIdHex(message.ID)).One(&result)
In reverse, you can use the method ObjectId.Hex()
detailed in this answer: Get ObjectIdHex value from mgo request
What you did in your code is a simple type conversion (assuming it message.ID
has a type string
) and the syntax is valid since the base type bson.ObjectId
is string
, so it interprets 24 characters as a type bson.ObjectId
, but this is not a valid value ObjectId
since it will be 24 bytes and not 12.
source to share