Home > Backend Development > Golang > Why Does My Go Program Get \'ObjectIDs Must Be Exactly 12 Bytes Long\' Error When Retrieving Documents by ID Using mgo?

Why Does My Go Program Get \'ObjectIDs Must Be Exactly 12 Bytes Long\' Error When Retrieving Documents by ID Using mgo?

DDD
Release: 2024-10-29 17:59:02
Original
327 people have browsed it

Why Does My Go Program Get

Unable to Retrieve Document ID Using mgo in Go

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template