Problem:
In a Go program using the mgo library to interact with a MongoDB database, the code to retrieve a document by ID fails with the error: "ObjectIDs must be exactly 12 bytes long (got 24)". A document with the specified ID exists in the database, but the query does not return any results.
Problem Code:
<code class="go">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)</code>
Cause:
The error message indicates that the provided ID is not a valid ObjectId. In this case, the problem lies in the conversion of the string ID to a bson.ObjectId.
Solution:
To properly convert a string representation of an ObjectId to a bson.ObjectId, use the bson.ObjectIdHex() function.
<code class="go">err = coll.FindId(bson.ObjectIdHex(message.ID)).One(&result)</code>
This function accepts a string containing the hexadecimal representation of the ObjectId and returns a valid bson.ObjectId value.
Explanation:
A bson.ObjectId is a 12-byte value represented as a string of 24 hexadecimal characters. The type conversion performed in the original code interpreted the 24-character string as the raw data for the bson.ObjectId, which resulted in an invalid 24-byte ObjectId. Using bson.ObjectIdHex() ensures that the string is correctly parsed and converted into a valid ObjectId with the appropriate byte length.
The above is the detailed content of Why Does My Go Program Get \'ObjectIDs Must Be Exactly 12 Bytes Long\' Error When Retrieving Documents by ID Using mgo?. For more information, please follow other related articles on the PHP Chinese website!